ABSTRACTION PROBLEMS OF
METHODS AND FUNCTIONS
Prob: There is a tight coupling of function names
with the UI client.
Solution: Rather than referring to the actual
methods in the UI / client if we can refer an
abstract pointer which in turn refers to the
methods then we can decouple the functions from
UI.
Later any change in the class ClsMath will not affect the UI as
the changes will be decoupled by the Abstract pointer. This
abstract pointer can be defined by using delegates. Delegates
define a simple abstract pointer to the function / method.
HOW TO DECLARE A DELEGATE?
To implement a delegate is a four step process declare,
create, point and invoke.
THE FIRST STEP
To declare the delegate with the same return type and
input parameters
Calling
int intResult =
objMath.getPointer(intOPeration).Invoke(intNu
mber1,intNumber2);
MULTICAST DELEGATES
create a delegate which can point to multiple
functions and methods. If we invoke such
delegate it will invoke all the methods and
functions associated with the same one after
another sequentially.
// Associate method1
delegateptr += Method1;
// Associate Method2
delegateptr += Method2;
// Invoke the Method1 and Method2 sequentially
delegateptr.Invoke();
// Create a simple delegate
public delegate void CallEveryOne();
obj.Show();
obj1.Show();
ptrcall += obj1.CallMe;
}
private void button1_Click(object sender,
EventArgs e)
{ // Invoke the delegate ptrcall.Invoke(); }
PROBLEM WITH MULTICAST DELEGATES
NAKED EXPOSURE
obj1.obj = this;
obj.Show();
obj1.Show();
EventCallEveryOne();
At the subscriber side i.e. (Form2 and Form3)
attach the method to the event listener.
obj.EventCallEveryOne += Callme;
DIFFERENCE BETWEEN DELEGATES AND
EVENTS
EXTENSION METHODS
An extension method is a special kind
of static method that allows you to add
new methods to existing types without creating
derived types.
The extension methods are called as if they
were instance methods from the extended type,
For example: x is an object from int class and we
called it as an instance method in int class.
public static class MyMathExtension
{
{ if (x <= 1) return 1;
if (x == 2) return 2;
}}
ANONYMOUS TYPES