Do C# 10 inferred delegate types involve an implicit conversion?

103 views Asked by At

Inferred delegate types have been introduced since C# 10.

However, I am quite confused with the behavior of the feature:

Generally, I think we can reasonably expect that, if this can compile:

var x = (my_expression); // inferred type
SomeType y = x;

This single assignment should compile as well:

SomeType y = (my_expression);

However, this is not satisfied when inferred delegate types are involved:

using System;

class Program {

    class FunctionWrapper<Output> {
        private Func<Output> WrappedFunction { get; }
        public FunctionWrapper(Func<Output> function) => WrappedFunction = function;
        public static implicit operator FunctionWrapper<Output>(Func<Output> function) => new FunctionWrapper<Output>(function);
    }

    public delegate void DoStuffDelegate<Inout>(ref Inout Input);

    static void Main(string[] args) {

        var funcLambda = () => "hello"; // type is inferred here...
        FunctionWrapper<string> funcWrapper = funcLambda;  // ... it compiles
        // but if we do a single assignment...
        FunctionWrapper<string> funcWrapper2 = () => "hello"; // CS1660 - this does not compile anymore... Why?

        // the exact opposite happens with delegates:

        // if we do a single assignment...
        DoStuffDelegate<string> delegWrapper2 = (ref string input) => { input = input + input; }; // ... it compiles
        // but if type is inferred...
        var delegateLambda = (ref string input) => { input = input + input; }; // type is inferred
        DoStuffDelegate<string> delegWrapper1 = delegateLambda; // CS0029 - this does not compile anymore...        
    }
}

I have the impression that inferred delegate types imply an implicit conversion at some stage, which probably should not be the case.

(link to the code: https://godbolt.org/z/3sbd9ndrT)

I tried different compilers and searched for documentation, discussions, and potential known issues regarding the behavior of inferred delegate types, unsuccessfully.

Can somebody please tell if this is a language/compiler defect, or if my expectations for these conversions to work are unreasonable?

Thank you in advance.

1

There are 1 answers

7
Paulo Morgado On

Looks like an issue with IDE0004.

You should report this issue