DEV Community

Discussion on: Understanding delegates in C# - did I get it right?

Collapse
 
peledzohar profile image
Zohar Peled

Both Method1() and GiveAction() are instance method (as apposed to static methods) and therefor there's no problem at all accessing Method1() from GiveAction(). Now, let's take a look at the code and add some comments to explain what's going on:

class Program
{
    // An instance field.
    int i = 4; 

    // The only static method in the class, also, the traditional starting point of c# applications.
    static void Main(string[] args)
    {
        // Set p as a new instance of the Program class.
        Program p = new Program(); 

        // Action y1 is initialized with the result of p.GiveAction() which is p.Method1().
        Action y1 = p.GiveAction(); 

        // This execute p.Method1(), so does the next row.
        y1();
        y1();
        Console.WriteLine();
    }

    // An instance method returning an Action.
    private  Action GiveAction()
    {
        return new Action(Method1);
    }

    // An instance method.
    public  void Method1()
    {
        this.i++;
    }
}