rohit
rohit

Reputation: 501

how does a delegate know which function to call in case of multiple subscribers

Say i have a delegate

public delegate void StringLogging(string msg);

Now class A uses this delegate to provide its own implementation, Also Class B provides its own implementation. Invocation list of StringLogging delegate contains two same methods i.e. one for Class A and one for Class B. How does a delegate know which function belongs to Class A and which one belongs to class B.

Upvotes: 2

Views: 292

Answers (2)

Hans Passant
Hans Passant

Reputation: 942338

This is carefully hidden in C#. But a delegate constructor takes two arguments, an object and a method group reference. It is much easier to see in the C++/CLI language, it doesn't have the same syntax sugar. For example, subscribing the Click event for a button looks like this:

 this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);

Note the first argument, the object reference of the object that implements the button1_Click method. The delegate type doesn't do anything special with that object reference, it simply stores it. The underlying field is Delegate.Target. It is used, later, when the delegate is invoked, to produce the also hidden this reference that an instance method needs.

The C# language doesn't permit the same syntax, the compiler infers the object reference from the method group reference you pass in the constructor. This prevents accidents. Do note the price of this syntax sugar, a C# programmer often doesn't realize that subscribing an event keeps a reference to the target object. Having that cause hard-to-diagnose leaks is a common mishap.

The explicit syntax in C++/CLI permits a feature that's entirely missing in C#, it supports unbound delegates. It is not especially useful, but it does model the way method pointers in C++ work. The probable reason C++/CLI didn't adopt the C# sugar.

Upvotes: 4

Tilak
Tilak

Reputation: 30728

Internally Delegates are implemented as MultiCastDelegate.

Delegate.GetInvocationList() returns Delegate[] which are corresponding to each methods associated with the main Delegate.

Delegate.Method is MethodInfo that has DeclaringType. This DeclaringType has the information whether class is Class A or Class B or some other type.

Upvotes: 4

Related Questions