0

I have two events in a class

public event AcquiredDataEvent OnNewAcquiredData;
public delegate void AcquiredDataEvent(int[] newData);

public ScanStartedEvent ScanStarted;
public delegate void ScanStartedEvent();

I just realized that ScanStarted does not have the keyword event before it. Most likely the result of a typo by me, though it still works as expected.

What is the difference between the two events if any?

klashar
  • 2,519
  • 2
  • 28
  • 38
KDecker
  • 6,928
  • 8
  • 40
  • 81

1 Answers1

1
  1. ScanStarted is not event. It's just a field of delegate type.
  2. It can be invoked outside of class where field is declated.
  3. It does not provide add/remove methods (that is what event is, like property is a pair of get/set methods) for attaching/removing event handlers - you can simply assign new delegate to ScanStarted field.

BTW Just like you can have property without backing field

public int Value
{
   get { return 42; }
   set { Console.WriteLine($"Haha, keep {value} for yourself"); }
}

You can have event without delegate field under the hood

public event AcquiredDataEvent OnNewAcquiredData
{
   add { Console.WriteLine("Trying to attach some handlers?"); }
   remove { Console.WriteLine("Haha, you should attach something first!"); }
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459