Is it possible to define a generic lambda in C#?

While Jared Parson's answer is historically correct (2010!), this question is the first hit in Google if you search for "generic lambda C#". While there is no syntax for lambdas to accept additional generic arguments, you can now use local (generic) functions to achieve the same result. As they capture context, they're pretty much what you're looking for.

public void DoSomething()
{
    // ...

    string GetTypeName<T>() => typeof(T).GetType().Name;

    string nameOfString = GetTypeName<string>();
    string nameOfDT = GetTypeName<DateTime>();
    string nameOfInt = GetTypeName<int>();

    // ...
}

While you cannot (yet?) have a generic lambda (see also this answer and one comment to this question), you can get the same usage syntax. If you define:

public static class TypeNameGetter
{
    public static string GetTypeName<T>()
    {
        return typeof( T ).Name;
    }
}

The you can use it (though using static is C# 6) as:

using static TypeNameGetter;
public class Test
{
    public void Test1()
    {
        var s1 = GetTypeName<int>();
        var s2 = GetTypeName<string>();
    }
}

It is not possible to create a lambda expression which has new generic parameters. You can re-use generic parameters on the containing methods or types but not create new ones.

Tags:

C#

Lambda

C# 3.0