Why can't C# infer the type of anonymous delegates/functions in some cases?

154 Views Asked by At

I'm using C# 12.

When assigning a function to an implicitly-typed (var) variable, C# can infer the type successfully, such as in this example:

// Scenario A
var func = () => "Hello World"; // no problem here, infers the type Func<string>

However, C# cannot infer the type when the function is used in a switch:

// Scenario B
// the type cannot be inferred, you must replace "var" with "Func<string>"
var func = true switch
{
    false => () => "Hello World",
    true => () => "Foo Bar"
};

Furthermore, you cannot instantly invoke a function unless you explicitly cast it to Func<string> first:

// Scenario C
var str = (() => "Hello World")(); // does not work

// Scenario D
var str = ((Func<string>)(() => "Hello World"))(); // works

Is there a technical reason why the type Func<string> cannot be inferred in all scenarios? I don't see why it couldn't, since Scenario A proves that it is possible to infer Func<string>. Is this a C# bug?

enter image description here

0

There are 0 best solutions below