Troskyvs
Troskyvs

Reputation: 8047

Could C# delegate point to another class/object's method?

Here, I wish to gain a delegate like function pointer, to point to a class method that's in another class (named Inner), and then pass it to a static function, like below:

public class Inner
{
    public int M = 3;
    public void F() { Console.WriteLine("f"); }
    public void G() { Console.WriteLine("g"); }
}
class Program
{
    public static void Caller(Action a)
    {
        a();
    }
    static void Main(string[] args)
    {
        var i = new Inner();
        var f = i.F;
        var g = i.G;
        f();//error
        g();//error
        Program.Caller(f);
        Console.WriteLine("Hello World!");
    }
}

I'm from c/c++, and in c/c++, function pointer like this is very straight forward, but this C# code fail to compile. I googled and found almost all delegate explanations talks about delegate that points to class method inside itself.

My question is, how to fix the code to make it work?

Upvotes: 1

Views: 1305

Answers (2)

Coding Seb
Coding Seb

Reputation: 93

You can not set methods group in implicit variables in C# so if you just change 2 var in Action it's working

public class Inner
{
    public int M = 3;
    public void F() { Console.WriteLine("f"); }
    public void G() { Console.WriteLine("g"); }
}
class Program
{
    public static void Caller(Action a)
    {
        a();
    }
    static void Main(string[] args)
    {
        var i = new Inner();
        Action f = i.F;
        Action g = i.G;
        f();
        g();
        Program.Caller(f);
        Console.WriteLine("Hello World!");
    }
}

Upvotes: 1

Johnathan Barclay
Johnathan Barclay

Reputation: 20353

Coding Seb's answer highlight's the cause of the issue, but doesn't really explain why.

It is because i.F is a method group, and not a specific method pointer. For example, imagine Inner was defined as so:

public class Inner
{
    public void F() { Console.WriteLine("f"); }
    public void F(string name) { Console.WriteLine(name); }
}

Which method would i.F refer to? F() or F(string)?

For that reason, you need to define the variable type explicitly, or cast the pointer:

Action f = i.F;

Or:

var f = (Action)i.F;

Upvotes: 2

Related Questions