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?
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.
Generics are type safe because generics are available at run time, It means the runtime knows what type of data structure you're using and can store it in memory more efficiently.
Yes, There are two level where you can apply generic type . You can apply generic type on Method level as well as Class level (both are optional).
Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
You can use Convert.ChangeType method, if the types you use implement IConvertible (all primitive types do).
Convert.ChangeType(value, targetType);
Have a look at the Convert.ChangeType method, I think it will meet your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With