Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic method return values

Tags:

c#

generics

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.

like image 549
Darren Young Avatar asked Jan 17 '11 11:01

Darren Young


1 Answers

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)));
}
like image 199
Maxim Gueivandov Avatar answered Oct 24 '22 19:10

Maxim Gueivandov