What's the difference between these two ways of adding delegates to a Generic List object?

D

Deckarep

Dear CSharp Group,

Both of these techniques work as expected but what is the better way of
doing this? Or does it even make a difference?

Method 1:

public delegate void MyDelegate(string s); //delegate

List<MyDelegate> listOfDelegates = new List<MyDelegate>(); //Generic
List of Delegates

listOfDelegates.Add( myFunc1 );
listOfDelegates.Add( myFunc2 );

Method 2:

listOfDelegates.Add( new MyDelegate(myFunc1) );
listOfDelegates.Add( new MyDelegate(myFunc2) );


So when I loop through my list I can call the functions and they both
work the same. Is one method more better then the other? All I can
tell is that the 2nd method I'm first creating a new Delegate and
passing in my function then adding it. The first method doesn't create
the new Delegate object.

So which is recommended and can I get bad side effects with one way or
the other?

Thanks in advance guys.
 
J

Jon Shemitz

Deckarep said:
Both of these techniques work as expected but what is the better way of
doing this? Or does it even make a difference?
public delegate void MyDelegate(string s); //delegate

List<MyDelegate> listOfDelegates = new List<MyDelegate>(); //Generic
listOfDelegates.Add( myFunc1 );
listOfDelegates.Add( myFunc2 );
listOfDelegates.Add( new MyDelegate(myFunc1) );
listOfDelegates.Add( new MyDelegate(myFunc2) );

No difference, except that your Method 1 is a bit smaller and clearer.

That is, "listOfDelegates.Add( myFunc1 );" uses a simplified syntax,
but if you use Reflector to look at your code, you'll see that it
generates the exact same CIL as "listOfDelegates.Add( new
MyDelegate(myFunc1) );".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top