What is the difference between using "new <DelegateName>" and just using <DelegateVariable> += FunctionName?  
Author Message
sofakng





PostPosted: Visual C# General, What is the difference between using "new <DelegateName>" and just using <DelegateVariable> += FunctionName? Top

I'm reading O'Reillys Programming in C# book and have come to the chapter on delegates and I'm a bit confused.

I understand exactly the purpose of them (eg. I've been using Delphi for several years and understand event-driven programming), but I'm a bit unsure on the syntax.

The book seems to use delegates in two different ways:

Example:
public delegate void NumberChangeHandler(int num);

public NumberChangeHandler OnNumberChange;

public void Example1(int num) { }
public void Example2(int num) { }

// The first way to setup the event handler:
OnNumberChange += Example1;
OnNumberChange += Example2;

// ...but the book seems to do it this way:
OnNumberChange += new NumberChangeHandler(Example1);
OnNumberChange += new NumberChangeHandler(Example2);

What's the difference between these two different ways It seems to me like the first way is much easier...



Visual C#5  
 
 
James Curran





PostPosted: Visual C# General, What is the difference between using "new <DelegateName>" and just using <DelegateVariable> += FunctionName? Top

The first way didn't work under C# v1.0. It was added to the syntax of C# v2 (released with VS2005 & .Net V2)

 
 
nobugz





PostPosted: Visual C# General, What is the difference between using "new <DelegateName>" and just using <DelegateVariable> += FunctionName? Top

Both ways generate the exact same code. The first way is just syntactic sugar for the second way. Behind the scenes, the compiler generates a constructor call for NumberChangeHandler().