Sponsored Ad

Friday, October 23, 2009

Delegate Example in C#

MathOperations In this example defines a class that has a couple of static methods to perform two The repo. Then you use delegates to call these methods. The math looks like this.

class MathOperations
{
public static double MultiplyByTwo(double value)
{
return value * 2;
}

public static double Square(double value)
{
return value * value;
}
}
You call up these methods like this:
using System;
namespace Wrox.ProCSharp.Delegates
{
delegate double DoubleOp(double x);
class Program
{
static void Main()
{
DoubleOp[] operations =
{
MathOperations.MultiplyByTwo,
MathOperations.Square
};
for (int i=0 ; i < operations.Length ; i++)
{
Console.WriteLine(“Using operations[{0}]:”, i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
Console.WriteLine();
}
}
static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
double result = action(value);
Console.WriteLine(
“Value is {0}, result of operation is {1}”, value, result);
}
}
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers