I am implementing a code generator in java that will create a C# code. When I need to use Console.ReadLine() the variable have a type, but I don't know the type when I am generating the code.
So, is it possible to convert the type from Console.ReadLine() only with the variable?
Code example:
public static void main()
{
var a = 1;
var b = 2;
/* The variable 'a' has a value and is of type integer,
* but when I generate this code I don't have this information */
a = Console.ReadLine();
/*I've tried to get type of variable but I didn't get success */
var type = a.GetType();
a = type.Parse(Console.ReadLine());
}
Convert.ChangeType(Console.ReadLine(), type);
learn.microsoft.com/en-us/dotnet/api/… | notice: return type of the method is object, would need to cast it to the desired type if object isn’t good enoughint.TryParse
to see if it's anint
. Failing, trydouble.TryParse
, failing that, check if it'strue
orfalse
, then check if it's a single character. That will tell you the type (and, for theTryParse
calls give you the value). One you have the type, do a normal parse or conversion