Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Delegate object to method with Func<> parameter

I have a method Foo4 that accepts a parameter of the type Func<>. If I pass a parameter of anonymous type , I get no error. But if I create and pass an object of the type 'delegate' that references to a Method with correct signature, I get compiler error. I am not able to understand why I am getting error in this case.

class Learn6
    {
        delegate string Mydelegate(int a);
        public void Start()
        {
            Mydelegate objMydelegate = new Mydelegate(Foo1);

            //No Error
            Foo4(delegate(int s) { return s.ToString(); });

            //This line gives compiler error.
            Foo4(objMydelegate);

        }

        public string Foo1(int a) { return a.ToString();}



        public void Foo4(Func<int, string> F) { Console.WriteLine(F(42)); }
    }
like image 724
pradeeptp Avatar asked May 30 '26 12:05

pradeeptp


2 Answers

It works if you pass a reference to the method directly:

Foo4(Foo1);

This is because actual delegates with the same shape are not inherently considered compatible. If the contracts are implicit, the compiler infers the contract and matches them up. If they are explicit (e.g. declared types) no inference is performed - they are simply different types.

It is similar to:

public class Foo
{
    public string Property {get;set;}
}

public class Bar
{
    public string Property {get;set;}
}

We can see the two classes have the same signature and are "compatible", but the compiler sees them as two different types, and nothing more.

like image 151
Rex M Avatar answered Jun 01 '26 00:06

Rex M


Because Func<int, string> and MyDelegate are different declared types. They happen to be compatible with the same set of methods; but there is no implicit conversion between them.

like image 33
itowlson Avatar answered Jun 01 '26 01:06

itowlson



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!