Mariusz Postol

Mariusz Postol

  • 395
  • 3.7k
  • 42.2k

Is the event or delegate a foundation for the inversion of control?

Apr 13 2024 3:14 PM

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: are built using the language support for delegates - an event is essentially a delegate with additional restrictions. For example, only the class containing the event can invoke it, while other classes can subscribe to listen to those events.

Inversion of Control (IoC): is a program design pattern used in software engineering to achieve loose coupling.  In sequential programming, it allows for a change in the natural sequence of instructions.

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

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)