Darren Young
Darren Young

Reputation: 11100

C# Generic method return values

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.

Upvotes: 14

Views: 44037

Answers (4)

Enigmativity
Enigmativity

Reputation: 117175

You cannot return either a double or an int from a generic method without it also returning any other type.

I might, for example, have a Foo class and your generic parse method, without any constraint, will allow this call to be made:

Foo result = Parse<Foo>("111");

The best that you can do with numbers is constrain on your function by only allowing struct (value-types) to be used.

T Parse<T>(string value) where T : struct;

But this will allow all number types, plus any other value-type.

You can constrain by interface type, but there isn't an INumeric interface on double or int so you're kind of stuck.

The only thing that you can do is throw an exception if the wrong type is passed in - which generally isn't very satisfying.

Your best approach, in this case, is to abandon generics and use separately named methods.

double ParseDouble(string value);
int ParseInteger(string value);

But, of course, this won't help you learn generics. Sorry.

Upvotes: 12

Maxim Gueivandov
Maxim Gueivandov

Reputation: 2385

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)));
}

Upvotes: 16

WestDiscGolf
WestDiscGolf

Reputation: 4108

You could do something like ...

   public TResult Parse<TResult>(string parameter)
    {
     /* do stuff */
    }

And use it like ...

int result = Parse<int>("111");

And then it will depend on your implementation in the Parse method.

Hope it helps.

Upvotes: 2

decyclone
decyclone

Reputation: 30840

Yes it's possible.

Example:

public T ParseValue<T>(String value) { 
    // ...
}

Upvotes: 9

Related Questions