Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a generic anonymous method?

Specifically, I want to write this:

public Func<IList<T>, T> SelectElement = list => list.First();

But I get a syntax error at T. Can't I have a generic anonymous method?

like image 701
mpen Avatar asked Dec 02 '10 19:12

mpen


1 Answers

Nope, sorry. That would require generic fields or generic properties, which are not features that C# supports. The best you can do is make a generic method that introduces T:

public Func<IList<T>, T> SelectionMethod<T>() { return list => list.First(); }

And now you can say:

Func<IList<int>, int> selectInts = SelectionMethod<int>();
like image 140
Eric Lippert Avatar answered Oct 05 '22 04:10

Eric Lippert