Search code examples
c#eventsmethods

Difference between Events and Methods


I have some confusion regarding Events. What are the basic differences between C# Events and Methods?


Solution

  • C# Events are a specific form of delegates. If you have programmed in other languages, like C++, you could compare a delegate to a function ("method") pointer - it points to some code in memory. When you call the pointer as a method, you actually call the method at the address the pointer points to.

    This is necessary to provide decoupling between the caller and the callee - so you don't have to have all methods ready when you publish code that calls them (which, wouldn't be possible - the Forms controls developers can't possibly know the code that needs to be called when a Button is pressed). You call the pointer, and the other developer sets it to an appropriate memory address later.

    P.S. delegates and Events however, have other advantages over plain function pointers - you can be sure that it will point to a good-looking method, taking the correct number and type of arguments and returning the correct type.