Is it possible to create a common Func <T> <T>

Is it possible to create a generic one Func<T><T>, as in Func, which takes a generic parameter and should return the type of this generic parameter?

In other words, can I do this?

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

Note that I have no context from the class or method, so I would like to do:

var user = createNull<User>();

Here is a bit more information on what I'm trying to do (note that the syntax is turned off because I donโ€™t know how to do this and itโ€™s not possible):

Func<TQuery, TResult><TQuery, TResult> query = q => 
    (TResult) handlers[Tuple.Create(typeof(TQuery), typeof(TResult))](q);

where the handlers are declared as follows:

var handlers = new Dictionary<Tuple<Type, Type>, Func<TQuery, TResult><TQuery, TResult>();
// examples
handlers.Add(Tuple.Create(typeof(ById), typeof(User)), 
             idQuery => new User());
handlers.Add(Tuple.Create(typeof(ByName), typeof(Customer)), 
             otherQuery => new Customer());

Then I would use queryas follows:

User result = query<User, IdQuery>(new ById{Id = 1});
Customer result1 = query<Customer, ByName>(new ByName());
+4
source share
2 answers

, , , :

static class CreateNull<T>
{
   public static Func<T> Default = () => default(T);
}

var createNull = CreateNull<User>.Default;
+5

. , .

Generics - , , . , :

public T DoSomething<T>(T input)

:

int result1 = DoSomething(1);
double result2 = DoSomething(2.0);
MyType result3 = DoSomething(new MyType());

JIT .

Lambdas, :

// Given generic Func<TInput, TResult>
Func<int, string> foo = (s) => Integer.parseInt(s);
0

All Articles