?
Solved

Adding to an event with or without "new."

Posted on 2008-11-15
2
Medium Priority
?
228 Views
Last Modified: 2012-05-05
Given the following code:


public delegate void MyDelegate();
class MyClass {
      public event MyDelegate MyEvent;
      public void MyFunction() {
            return;
      }
}


... In most online articles that I've read that explain how events work in C#, the author instructs the programmer to add MyFunction to MyEvent using the following syntax:


MyEvent += new MyDelegate(MyFunction);


However, I have ALWAYS been able to just do this:


MyEvent += MyFunction;


Can someone please explain to me the difference between the two, and why I should ever want to use the first method?

I prefer the second method because it's more concise, and because it looks syntactically the same as the method for *removing* a function from an event, i.e. MyEvent -= MyFunction.

0
Comment
Question by:MiloDC
2 Comments
 
LVL 26

Accepted Solution

by:
Anurag Thakur earned 500 total points
ID: 22969516
As per MSDN article there is no difference between the two methods
http://msdn.microsoft.com/en-us/library/ms366768(VS.80).aspx
And the shortcut that you have been using has been added in the 2.0 framework

The only argument that i will be giving for using the syntax with new is that it will indicate which delegate i am referencing to (more readable).
I will prefer readability over lesser code as in longer run for code maintenance readable code is better than shorter code
0
 

Author Comment

by:MiloDC
ID: 22969534
OK, so it's necessary to do it the first way ("new") only in C# 1.0.

Thanks!
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Loops Section Overview

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question