DEV Community

Bruce Axtens
Bruce Axtens

Posted on

3

Understanding delegates in C# - did I get it right? Part 2

The young man wrote back, unpacking his original question a little. This is what he said following by my response. Am I right?

Now I am interested to know that in GiveAction() method, when we pass the reference of Method1, we directly write the name Method1. Normally when we call a non static method we need to write the instance variable first then we write the name of method in which we are interested.

I don't think I'm understanding the question. But I'll keep trying.

When you're giving Method1 to the return value of GetAction that's getting resolved at compile time for the instance-local method of the same name.

Your code from last time could be written like this:

using System;
using System.Diagnostics;

class Program
{
    int i = 4;
    static void Main(string[] args)
    {
        Debugger.Launch();
        Program p = new Program();
        Action y1 = p.GiveAction();
        y1();
        y1();
        Console.WriteLine(p.i);
    }
    private Action GiveAction()
    {
        Action ga = Method1;
        return ga;
        /*
        this also works

        return (Action)Method1;
        */
    }
    public void Method1()
    {
        this.i++;
    }

}
Enter fullscreen mode Exit fullscreen mode

Notice the two different ways of specifying the return value of GiveAction. That and the way you were doing it originally all hand back an Action delegate to Main which gets stored in the Action delegate named y1.

GiveAction and Method1 are both executing in the context of the instantiated Program object stored in p. They don't need further qualification because they are not objects themselves that need to be instantiated.

کیا میں قریب ہوں؟

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay