Ok, suppose you define a delegate in some class.
public delegate void StringDelegate (string s);
and another class implements a method :
public static void StringWriter (string s) {...}
In the book that I'm reading "Programming C#" 4th ed they create delegates using the new keyword, ex:
ClassDelegate.StringDelegate writer;
writer = new ClassDelegate.StringDelegate (DelegateImplementer.StringWriter);
writer("Hello");
However, I see one can also call the delegate method this way
ClassDelegate.StringDelegate writer;
writer = DelegateImplementer.StringWriter;
writer ("Hello");
What's the difference? Why do I want instantiate and create an object delegate when I can just simply pass or make reference to the signature of the method delegate.
Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Delegates are mainly used in implementing the call-back methods and events. Delegates can be chained together as two or more methods can be called on a single event. It doesn't care about the class of the object that it references. Delegates can also be used in “anonymous methods” invocation.
In the United States Congress delegates are elected to represent the interests of a United States territory and its citizens or nationals. In addition, certain US states are governed by a House of Delegates or another parliamentary assembly whose members are known as elected delegates.
There is absolutely no difference between the two statements. writer = DelegateImplementer.StringWriter;
still creates a delegate
object; the compiler will generate the new ClassDelegate.StringDelegate ()
for you. It's just a cleaner syntax that was added in C# 2.0.
As @Ben Voigt mentioned in his answer is only required in C# 2.0 where the compiler can't deduce the type of the delegate, when using Control.Invoke() for example.
Sometimes the correct type can't be deduced (like when you're calling a generic), in such a case you need to let the compiler know what kind of delegate you want.
Most of the time, though, naming the method group is easier and clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With