3 ways to instantiate the same c# delegate Type

In c++ or java, you can instantiate a class Animal many ways, like
Animal myCat; // exactly like declaring an int variable
Animal myCat(2); //age
Animal* myCat = new Animal(“kit”);

C# delegate is more complicated. http://www.yoda.arachsys.com/csharp/events.html has a concise list of about 5 different ways to Instantiate a delegate Type. Extremely insightful. Among other things, it reveals that in the instance method case the delegate Instance must “remember” the target

public delegate string FirstDelegate (int x); // type declaration.
 
// The following two creation expressions are equivalent,
// where InstanceMethod is an instance method in the class
// containing the creation expression (or a base class).
// The target is "this".
FirstDelegate d1 = new FirstDelegate(InstanceMethod);
FirstDelegate d2 = new FirstDelegate(this.InstanceMethod);

// Here we create a delegate instance referring to the same method
// as the first two examples, but with a different target.
FirstDelegate d3 = new FirstDelegate(anotherInstance.InstanceMethod);

// This delegate instance uses an instance method in a different class (and 
// obviously different target),
// specifying the target to call the method on
FirstDelegate d4 = new FirstDelegate(instanceOfOtherClass.OtherInstanceMethod);

// This delegate instance uses a static method in host class containing
// the creation expression (or a base class). Target is NULL for ALL static
FirstDelegate d5 = new FirstDelegate(StaticMethod);

// This delegate instance uses a static method in a different class
FirstDelegate d6 = new FirstDelegate(OtherClass.OtherStaticMethod);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s