Instantiating a delegate

  • Thread starter Thread starter Peter
  • Start date Start date
P

Peter

Hi

in some example code I have seen delegates instantiated in the
following fashion:

public delegate string UserName(int id);


UserHelper helper = new UserHelper();

UserName un = new UserName(helper.GetUsername);


But I have found that the following also seems to work:

UserName un = helper.GetUsername;


Is this correct?



Thanks,
Peter
 
Peter said:
in some example code I have seen delegates instantiated in the
following fashion:

public delegate string UserName(int id);


UserHelper helper = new UserHelper();

UserName un = new UserName(helper.GetUsername);


But I have found that the following also seems to work:

UserName un = helper.GetUsername;


Is this correct?
Yes, C# 2.0 made the compiler capable of inferring and automagically
instantiating the appropriate delegate type. Many people (and even Visual
Studio) still use the syntax from 1.0, but it's redundant.
 
Peter,

From C# 2.0 and on it works. The compiler will basically expand the
delegate instantiation out for you. It's a shorthand that I find very
convenient.

- Nick
 
I wish the automatic code completion (when you hit tab) would use the new
syntax. I really dislike the way it uses the old syntax!
 
Peter said:
in some example code I have seen delegates instantiated in the
following fashion:

public delegate string UserName(int id);


UserHelper helper = new UserHelper();

UserName un = new UserName(helper.GetUsername);


But I have found that the following also seems to work:

UserName un = helper.GetUsername;


Thanks for the answers. In my naivety I had used the form:
UserName un = helper.GetUsername
without thinking about it - to me it seems natural.
It was only later I saw the "real" syntax.

/Peter
 
Back
Top