I want to convert a string to a generic type like int
or date
or long
based on the generic return type.
Basically a function like Parse<T>(String)
that returns an item of type T
.
For example if a int was passed the function should do int.parse
internally.
Casting does not create a new object, It will only assign a reference of one datatype to reference of another datatype, only if its assignable. Parsing : Parsing, on the other side, is converting from one data type to another, like from string to int for example. This Creates a new Object, and returns reference to it.
Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str); Here, str is a string that contains a number to convert.
Parse strings in . A parsing operation converts a string that represents a . NET base type into that base type. For example, a parsing operation is used to convert a string to a floating-point number or to a date-and-time value. The method most commonly used to perform a parsing operation is the Parse method.
System.Convert.ChangeType
As per your example, you could do:
int i = (int)Convert.ChangeType("123", typeof(int)); DateTime dt = (DateTime)Convert.ChangeType("2009/12/12", typeof(DateTime));
To satisfy your "generic return type" requirement, you could write your own extension method:
public static T ChangeType<T>(this object obj) { return (T)Convert.ChangeType(obj, typeof(T)); }
This will allow you to do:
int i = "123".ChangeType<int>();
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