1. What's delegate in C #?
A delegate is an object, that knows how to call a method.
A delegate type defines the kind of method that delegate instances can call. Specifically,
It defines the method ' return type and its parameter types.
The Followingdefines a delegate type called Transformer:
delegate int Transformer (int x);
Transformer is compatible with any method with an int return type and a single
int parameter, such as this:
static int Square (int x) {return x * x;}
Assigning a method to a delegate variable creates a delegate instance:
Transformer t = Square;
Complete code:
Public Delegate intTransformer (intx);classutil{ Public Static voidTransform (int[] values, Transformer t) { for(inti =0; I < values. Length; i++) Values[i]=T (Values[i]); }}classtest{Static voidMain () {int[] values = {1,2,3 }; Util.transform (values, Square); //Hook in the Square method foreach(intIinchvalues) Console.Write (i+" ");//1 4 9 } Static intSquare (intx) {returnX *x;}}
C # 5 in a nutshell-delegate