The declaration of a delegate type is similar to a method signature. It has a return value and any number of parameters of any type
A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. For applications of delegates, see Delegates and Generic Delegates.
The delegate must be instantiated with a method or lambda expression that has a compatible return type and input parameters. For more information on the degree of variance that is allowed in the method signature, see Variance in Delegates (C# and Visual Basic). For use with anonymous methods, the delegate and the code to be associated with it are declared together. Both ways of instantiating delegates are discussed in this section.
Syntax:public delegate void TestDelegate(string message);
public delegate int TestDelegate(MyType m, long num);
Example:// Declare delegate -- defines required signature:
delegate double MathAction(double num);
class DelegateTest
{
// Regular method that matches signature:
static double Double(double input)
{
return input * 2;
}
static void Main()
{
// Instantiate delegate with named method:
MathAction ma = Double;
// Invoke delegate ma:
double multByTwo = ma(4.5);
Console.WriteLine("multByTwo: {0}", multByTwo);
// Instantiate delegate with anonymous method:
MathAction ma2 = delegate(double input)
{
return input * input;
};
double square = ma2(5);
Console.WriteLine("square: {0}", square);
// Instantiate delegate with lambda expression
MathAction ma3 = s => s * s * s;
double cube = ma3(4.375);
Console.WriteLine("cube: {0}", cube);
}
// Output:
// multByTwo: 9
// square: 25
// cube: 83.740234375
}
License.
All information of this service is derived from the free sources and is provided solely in the form of quotations.
This service provides information and interfaces solely for the familiarization (not ownership) and under the "as is" condition.
Copyright 2016 © ELTASK.COM. All rights reserved.
Site is optimized for mobile devices.
Downloads: 4214 / 159167652. Delta: 0.00142 с