I'm just learning about generics and have a question regarding method return values.
Say, I want a generic method in the sense that the required generic part of the method signature is only the return value. The method will always take one string as it's parameter but could return either a double or an int. Is this possible?
Effectively I want to take a string, parse the number contained within (which could be a double or an int) and then return that value.
Thanks.
Something like this?
void Main()
{
int iIntVal = ConvertTo<int>("10");
double dDoubleVal = ConvertTo<double>("10.42");
}
public T ConvertTo<T>(string val) where T: struct
{
return (T) System.Convert.ChangeType(val, Type.GetTypeCode(typeof(T)));
}
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