Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 563
KyleMit Avatar asked Oct 27 '25 15:10

KyleMit


1 Answers

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:

  • A delegate of type Func or Action
  • Or an expression tree of type Expression (which can then be compiled to a delegate)

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

  • delegate keyword vs. lambda notation
  • How to return value with anonymous method?
like image 197
KyleMit Avatar answered Oct 29 '25 05:10

KyleMit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!