C# Generic Generics (A Serious Question)

Posted by tahirhassan on Stack Overflow See other posts from Stack Overflow or by tahirhassan
Published on 2010-05-24T14:22:42Z Indexed on 2010/05/24 14:41 UTC
Read the original article Hit count: 136

Filed under:
|
|

In C# I am trying to write code where I would be creating a Func delegate which is in itself generic. For example the following (non-Generic) delegate is returning an arbitrary string:

Func<string> getString = () => "Hello!";

I on the other hand want to create a generic which acts similarly to generic methods. For example if I want a generic Func to return default(T) for a type T. I would imagine that I write code as follows:

Func<T><T> getDefaultObject = <T>() => default(T);

Then I would use it as

getDefaultObject<string>() which would return null and if I were to write getDefaultObject<int>() would return 0.

This question is not merely an academic excercise. I have found numerous places where I could have used this but I cannot get the syntax right. Is this possible? Are there any libraries which provide this sort of functionality?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics