Reputation: 3524
I'm trying to create a generic method to cast an object, but can't seem to crack that chestnut. (It's Friday 3pm, been a long week)
Ok, so I have this scenario:
// We have a value (which .net sets as a double by default)
object obj = 1.0;
// We have the target type as a string, which could be anything:
// say string sometType = "System.Decimal"
Type type = Type.GetType(someType);
// I need a generic way of casting this
object castedObj = (xxx) obj;
How can I cast that object generically without creating an endless number of if-else-staments?
Upvotes: 12
Views: 9199
Reputation: 40863
You can do something like the following:
Type underlyingType = Type.GetType(someType);
if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
{
var converter = new NullableConverter(underlyingType);
underlyingType = converter.UnderlyingType;
}
// Try changing to Guid
if (underlyingType == typeof (Guid))
{
return new Guid(value.ToString());
}
return Convert.ChangeType(value, underlyingType);
Kudos to Monsters Go My.net for the change type function
Upvotes: 0
Reputation: 62940
You can use Convert.ChangeType method, if the types you use implement IConvertible (all primitive types do).
Convert.ChangeType(value, targetType);
Upvotes: 18
Reputation: 25001
You can't cast it to a type you specify dynamically.
You may consider using generics instead, but I would need more code to see how it can help you.
Upvotes: 0
Reputation: 49261
Have a look at the Convert.ChangeType method, I think it will meet your needs.
Upvotes: 3