Delegates |
{
double dResult = (iValueX + iValueY)
* dFactor;
Console.WriteLine( "Instance
Results: {0}", dResult );
return dResult;
}
public static double ComputeStatic( int
iValueX, int iValueY ) // static method
{
double dResult = (iValueX + iValueY)
* 0.5;
Console.WriteLine( "Static
Result: {0}", dResult );
return dResult;
}
private double dFactor;
}
public class MyComputer
{
static void Main()
{
Computer oComputer1 = new
Computer( 0.69 );
Computer oComputer2 = new
Computer( 0.76 );
ComputeOutput delegate1 = new
ComputeOutput (oComputer1.ComputeInstance );
ComputeOutput delegate2 = new
ComputeOutput (oComputer2.ComputeInstance );
// points to a static method - use method group conversion
// points to a static method - use method group conversion
ComputeOutput delegate3 =
Computer.ComputeStatic;
double dTotal = delegate1( 7, 8
) + delegate2( 9, 2 ) + delegate3( 4, 3 );
Console.WriteLine( "Output:
{0}", dTotal );
}
}
Method Group Conversion allows you to simply assign the
name of a method to a delegate, without usingnew or explicitly invoking
the delegate’s constructor.
Computer.StaticCompute is actually called a method group because the method could be overloaded and this name could refer to a group of methods. In this case, the method group Computer.StaticCompute has one method in it.
Computer.StaticCompute is actually called a method group because the method could be overloaded and this name could refer to a group of methods. In this case, the method group Computer.StaticCompute has one method in it.
C# allows you to directly assign a delegate from a method
group. When you create the delegate instances via new, you pass the method
group in the constructor
What is delegate, use of delegate in c# sharp dot .Net, real
world scenarios and live code example of delegate, C# allows you to directly
assign a delegate from a method group