Mariusz Postol

Mariusz Postol

  • 420
  • 3.7k
  • 42.6k

Is the event or delegate variable a foundation for the polimorfizm?

Apr 13 2024 2:11 PM

Delegates: Delegates are a fundamental construct in C# that enables late binding scenarios allowing the definition of a type-safe reference to a method, which can then be invoked dynamically at runtime. In essence, delegates provide a way to call methods indirectly, allowing for flexibility in method invocation.

Events: Events are built using the language support for delegates - an event is essentially a delegate with additional restrictions. Only the class containing the event can invoke it, while other classes can subscribe to listen to those events.

The event, delegate type, and delegate variable definitions are in the DelegateExample class as follows:

   public delegate int PerformCalculation(int x, int y);
   public PerformCalculation PerformCalculationVar;
   public event EventHandler PerformSumMethodCalled;
      DelegateExample _newInstance = new DelegateExample();
      _newInstance.PerformCalculationVar = _newInstance.PerformSumMethod;
...
      _newInstance.PerformSumMethodCalled += (x, y) => { _Called++; _sender = x; _args = y; };

Check out the DelegateExampleUnitTest unit test class to get more.


Answers (1)