Search code examples
c#.netlambdadelegatesc#-10.0

Feature 'inferred delegate type' is not available in C# 9.0


I'm trying to write the following code:

var name = "Kyle";
var sayHello = () => $"Hello, {name}";
Console.WriteLine(sayHello());

But I get the error:

Feature 'inferred delegate type' is not available in C# 9.0.

What does that mean and how can I fix it?


Solution

  • Problem

    The problem is the actual lambda expression itself () => $"Hello, {name}" does not actually have a type (yet).

    It is only typed once it's cast to either:

    Solution in C#10

    C#10 made several lambda improvements including an inferred delegate type, meaning C# can now determine (infer) that the lambda is going to be used as a delegate function - so the original syntax is available upon upgrade to C#10:

    var sayHello = () => $"Hello, {name}";
    

    Previous Solutions

    If you can't upgrade to C#10, there are a couple ways you can explicitly type the lambda.

    You can provide an explicit type instead of using var:

    Func<string> sayHello = () => $"Hello, {name}";
    

    Or you can use the func constructor to type the expression:

    var sayHello = new Func<string>(() => $"Hello, {name}");
    

    Demo in .NetFiddle

    Further Reading