I am attempting to dynamically cast a variable to any type from a string in c#. Here is an example:
string str = "System.Int32";
Type t = System.Type.GetType(str);
string v = "100";
System.Int32 x = Convert.ChangeType(v,t);
The error that is displayed at design-time is:
Cannot implicitly convert type 'object' to 'int.' An explicit conversion exists (Are you missing a cast?)
What is the easiest way to accomplish this? I realize that the example above shows casting to an int32, but that is purely for the example. I do not know the type ahead of time. I apologize for not making that clear on my original question.
System.Int32 x = (System.Int32)Convert.ChangeType(v,t);vis going to be anint, what's the point of getting the type in astring? Apparently you don't needtin this specific case at all.Convert.ToInt32if you are only going to deal with integers