Delegate definition
is almost similar to method declarations.Syntax
<accessmodifier> delegate <methoddeclaration>Example
public delegate int Calc(int a, int b);
Delegate variable declaration
is just like variable declarationSyntax
<delegatetype> <delegatevariable>Example
Calc c;
Method assignment to delegates
To use a delegate, we have to associate a method to the delegate instance.Method to be associated to a delegate should match the signature of the delegate, which includes parameter types and return types
Example
public int Add(int x, int y)
{
return x+y;
}
Instantiating delegates
Syntaxnew <delegatetype>(<methodname>)Example
Calc c= new Calc(Add);
Using a delegates
Delegates are basically used to invoke a method which is associated to it..Net automatically adds few methods to it which enables us to invoke the method.
Here Invoke(int a, int b) will be added to Calc delegate.
Methods associated with the delegates can be invoked using the following syntax
Syntax
<delegatevariable>.Invoke(<parameters>)Example
int x = c.invoke(10, 20);
There is another simple shortcut for this.
Syntax
<delegatevariable>(<parameters>)Example
int x = c(10, 20);
No comments:
Post a Comment