2

I want to make a list that stores some events and attach event handler to the event through the list.

So I make a List<dele> add the event anEvent into it, then I try to attach an event handler to that event, but at last anEvent still got no event handler attached to it, the program outputs True. But the delegate stored at list[0] did get the lambda expression.

 public delegate void dele();

class Program
{
   static event dele anEvent;
    static void Main(string[] args)
    {
        List<dele> list=new List<dele>();
        list.Add(anEvent);
        list[0]+=()=>{Console.WriteLine("BEEP!");};
        Console.WriteLine(anEvent==null);
    }
}

Isn't delegate a reference type? It seems that eventhandler and list[0] refers to different objects. I wonder why.

If I want that anEvent gets the event handler when I attach the handler to list[0], what should I do?

Thanks!

Lee
  • 520
  • 5
  • 13

1 Answers1

1

A delegate is basically a contract for a method implementation. Kinda like an interface is a contract for class implementations.

The CLI (Common Language Infrastructure) specification says that delegates are reference types.

A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. For applications of delegates, see Delegates and Generic Delegates.

Have a look at this question and also have a look at that one.

I have converted the method into a non anonymous method for debugging reasons

 public delegate void dele();
 public static event dele anEvent;

  static void Main(string[] args) {
      List<dele> list = new List<dele>();
      list.Add(anEvent);
      list[0] += Dele;
      list[0].Invoke(); //this actually gets invoked and does not throw!
      anEvent = list[0];
      Console.WriteLine(anEvent == null); //the output is false
      anEvent.Invoke(); // this also gets s invoked and does not throw
  }

private static void Dele() { //this gets invoked 2 times as expected
  Console.WriteLine("Beep"); // this gets printed after invoking the event
}
Tobias Theel
  • 3,088
  • 2
  • 25
  • 45
  • I'm sorry for that. The statement anEvent=list[0]; shouldn't has been there. I removed it. Then the output will be Beep and true. That means anEvent didn't get Dele and list[0] got, do I think it right? But why? Delegate is reference type then why did list[0] and anEvent get different value? – Lee Sep 02 '17 at 09:26
  • I think I got it. So when I pass `anEvent` to the `List.Add` method, it actually copies the delegate in the event, then I attach an event handler to the delegate stored in `list[0]`,because delegate is an immutable type so it doesn't affect the delegate in `anEvent`, for this reason it won't work. Is that right? – Lee Sep 02 '17 at 14:45