Possible Duplicate:
is there a generic Parse() function that will convert a string to any type using parse?
I want to make a generic function for doing some operations, like:
ConvertValue<T>(string value)
If T
is int
then the function will convert the value to int
and return the result.
Similarly, if T
is boolean
, the function will convert the value
to boolean
and return it.
How to write this?
In the general case, a generic type could be both a supplier and a consumer of its type parameters, which means that the type we get by casting the type parameter (up or down) cannot be either a subtype or a supertype of the original: they are unrelated types that cannot be cast between, which is exactly why the Java ...
Generic MethodsAll generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.
By passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
Something like this?
public static T ConvertValue<T>(string value) { return (T)Convert.ChangeType(value, typeof(T)); }
You can then use it like this:
int val = ConvertValue<int>("42");
Edit:
You can even do this more generic and not rely on a string
parameter provided the type U
implements IConvertible
- this means you have to specify two type parameters though:
public static T ConvertValue<T,U>(U value) where U : IConvertible { return (T)Convert.ChangeType(value, typeof(T)); }
I considered catching the InvalidCastException
exception that might be raised by Convert.ChangeType()
- but what would you return in this case? default(T)
? It seems more appropriate having the caller deal with the exception.
While probably not as clean looking as the IConvertible
approach, you could always use the straightforward checking typeof(T)
to return a T
:
public static T ReturnType<T>(string stringValue)
{
if (typeof(T) == typeof(int))
return (T)(object)1;
else if (typeof(T) == typeof(FooBar))
return (T)(object)new FooBar(stringValue);
else
return default(T);
}
public class FooBar
{
public FooBar(string something)
{}
}
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