8

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.

user990692
  • 543
  • 1
  • 8
  • 16
  • I often use the former because that is what VS auto-completes to after a `+=` ;-) About the only other time I use named delegates is in parameters to function calls, in which case the latter is the much cleaner choice. –  Oct 12 '11 at 04:23
  • possible duplicate of [C# Delegate Instantiation vs. Just Passing the Method Reference](http://stackoverflow.com/questions/2181282/c-sharp-delegate-instantiation-vs-just-passing-the-method-reference) – nawfal Jul 06 '14 at 20:32

5 Answers5

7

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.

shf301
  • 31,086
  • 2
  • 52
  • 86
4

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
4

The two are equivalent. The latter is syntax new with C# 2.0.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
1

Both are the same, but the latter syntax was added in C#2 to simplify delegate usage.

Both methods compile to the same byte code.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
1

It's syntactic sugar. Ultimately both sets of code do the same thing.

I'd also note that .Net has a bunch of generic delegates built in that can save you alot of coding. In this case I'd do:

Action<string> writer;
writer = DelegateImplementer.StringWriter;
writer ("Hello");

This way you don't even need to create your own delegate.

Dylan Smith
  • 22,069
  • 2
  • 47
  • 62