-1

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; }

user3163495
  • 2,425
  • 2
  • 26
  • 43
  • 2
    Why don’t you want to use a lambda expression? `new Func<…>(delegate(…))` and `delegate(…)` are virtually deprecated syntaxes as there were superseded by Lambda expressions. That you need to declare Func<…> is probably to differentiate it from Expression> as delegates as well as expressions use the same lambda syntax. – ckuri May 16 '21 at 18:13
  • Does this answer your question? [Local function vs Lambda C# 7.0](https://stackoverflow.com/questions/40943117/local-function-vs-lambda-c-sharp-7-0) and [Local functions and SOLID principles C#](https://stackoverflow.com/questions/50635937/local-functions-and-solid-principles-c-sharp) –  May 16 '21 at 18:33
  • 1
    [Local functions (C# Programming Guide)](https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/local-functions) –  May 16 '21 at 18:34

1 Answers1

0

The only way I know is to use a closure. Then at least the parameter can be omitted.

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

What i don't understand is why not use lambda. In this case, lambdas are the means of choice to make it shorter.

MK-NEUKO
  • 90
  • 8