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?
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:
Func
or Action
Expression
(which can then be compiled to a delegate)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}";
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}");