Search code examples
c#eventsdelegatesnew-operatorfunction-reference

How new operator works with delegates in C#


In this code snippet how does new MyDel(this.WelcomeUser) work? What happens in memory, I know that delegate is reference type, so is there an object created in heap and which type of object is it - MyDel? what is exactly this.WelcomeUser? Is it a reference to a method?

using System;
namespace SampleApp {
public delegate string MyDel(string str);

class EventProgram {
  event MyDel MyEvent;

  public EventProgram() {
     this.MyEvent += new MyDel(this.WelcomeUser);
  }
  public string WelcomeUser(string username) {
     return "Welcome " + username;
  }
  static void Main(string[] args) {
     EventProgram obj1 = new EventProgram();
     string result = obj1.MyEvent("Tutorials Point");
     Console.WriteLine(result);
  }
 }
}

Solution

  • how does new MyDel(this.WelcomeUser) work?

    It is a call to a constructor, with this.WelcomeUser as an argument.

    public delegate string MyDel(string str);
    

    Is a Type definition. The compiler uses this to generate a class deriving from System.Delegate. Note that this was designed before C# had generics.

    what is exactly this.WelcomeUser?

    It is the name of a method. In C# (and C, C++ etc) a method is always followed by a parameter (or argument) list, even if that list is empty: SomeMethod().
    Omitting the list is the equivalent of adress-of.

    It becomes clearer when you look at VB.NET, the equivalent code is

    MyEvent += new MyDel(this.WelcomeUser);       // C#
    
    AddHandler MyEvent, AddressOf Me.WelcomeUser  ' VB
    

    And from C# 2 on, you can use the short notation:

    MyEvent += this.WelcomeUser;       // modern C#