Search code examples
c#delegates

Without using a lambda, Is there a shorter way of declaring a Func (delegate) variable in C#?


So far I know of two different ways to declare a Func variable using a delegate.

Technique 1

var AddTen = new Func<int, int>(delegate (int input)
{
    return input + 10;
});

Technique 2

Func<int, int> AddTen = delegate (int input)
{
    return input + 10;
};

Without using a lambda expression, is there any shorter way to define a Func? It just always seems redundant to me to have to use Func<int, int> even though it looks like the type can be inferred from delegate(int) { return int; }


Solution

  • Newer versions of C# allow you to use the var keyword with delegates:

    var AddTen = delegate (int input)
    {
        return input + 10;
    };