Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand when calling generic methods in c#

If I have the method

void foo<T>(T bar){}

I can successfully call it like this:

string s = string.Empty;
foo(s);

As I imagine the compiler/runtime can infer the type,

However If I change the method to this:

T foo<T,T2>(T2 bar){...}

Then I must call it in 'full', specifying both the input parameter type and the return type:

string s = string.Empty;
foo<int,string>(s);

Is there a way I can shorthand this so I dont need to specify the input parameter(s) type? I.E.

foo<int>(s);

Thanks

like image 565
maxp Avatar asked Dec 09 '11 11:12

maxp


1 Answers

You could always rewrite your method to:

void foo<T, U>(U bar, out T baz)
{
    baz = default(T);
}

if you really want the type inference... Now:

string s = string.Empty;
int i;

foo(s, out i);

will work just fine.

Also, see: this question for an excellent answer by Eric Lippert as to why you can't have what you want!

EDIT: I realise I didn't actually answer your question...

Is there a way I can shorthand this so I dont need to specify the input parameter(s) type?

Simply put... No.

like image 129
Simon Cowen Avatar answered Oct 17 '22 19:10

Simon Cowen