Reputation: 455
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.
Upvotes: 0
Views: 393
Reputation: 43636
You could make a hepler method to make it a bit easier
public T ConvertTo<T>(object obj) where T : IConvertible
{
try
{
return (T)Convert.ChangeType(obj, typeof(T));
}
catch
{ // handle as needed/required
}
return default(T);
}
Usage:
string v = "100";
int value = ConvertTo<int>(v);
Or Extension method:
public static class Extensions
{
public static T ConvertTo<T>(this object obj) where T : IConvertible
{
try
{
return (T)Convert.ChangeType(obj, typeof(T));
}
catch
{ // handle as needed/required
}
return default(T);
}
}
Usage:
string v = "100";
int value = v.ConvertTo<int>();
Upvotes: 1
Reputation: 9847
If you know the type that you're trying to convert to, you should just cast it to that type:
int x = (int)Convert.ChangeType(v, t);
It might also be nice to have a generic method to perform the cast for you:
public static class ConvertHelper
{
public static T ChangeType<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
}
...
int x = ConvertHelper.ChangeType<int>(v);
Upvotes: 0
Reputation: 755457
The ChangeType
function has a return type of Object
. You need to explicitly cast to Int32
System.Int32 x = (System.Int32)Convert.ChangeType(v,t);
Couple of other minor points
int
instead of System.Int32
"System.Int32"
use typeof(int).FullName
Upvotes: 1