komodosp
komodosp

Reputation: 3618

c# access owner object from delegate function

Can I access an object that contains a delegate from within that delegate?

e.g.

class Salutation {

     public string OtherParty {get; set;}
     public AddressDelegate GreetingDelegate {get; set;}

}

public delegate void AddressDelegate ();

Then...

void Main() {
    Salutation hello = new Salutation { 
        OtherParty = "World",
        GreetingDelegate = new AddressDelegate(HelloSayer)
    };

    hello.GreetingDelegate();
}

private void HelloSayer() {
    Console.WriteLine(string.Format("Hello, {0}!", OtherParty));  
}

So is it possible to refer to the OtherParty property from the Salutation class from within the HelloSayer function, or do I need to pass the data as a parameter to the function?

Upvotes: 2

Views: 1281

Answers (2)

mybirthname
mybirthname

Reputation: 18127

    static void Main(string[] args)
    {
        Salutation hello = new Salutation();
        hello.OtherParty = "World";
        hello.GreetingDelegate = new AddressDelegate(HelloSayer);

        hello.GreetingDelegate(hello.OtherParty);
        Console.ReadKey();
    }

    public delegate void AddressDelegate(string otherParty);

    private static void HelloSayer(string otherParty)
    {
        Console.WriteLine(string.Format("Hello, {0}!", otherParty));
    }

Like Andrey said you need to pass it, here is the example.

Upvotes: 2

Andrey
Andrey

Reputation: 60065

You need to pass it. Delegate know nothing about owner object. Because it is not an owner, it is just an object that happens to have a reference to this delegate.

Upvotes: 3

Related Questions