Click to See Complete Forum and Search --> : delegates


ncs
June 27th, 2002, 03:01 PM
Could anyone give me an explanation of delegates and give a practical use for one. I have read about them, and don't quite understand what they are and why you would use them. Thanks:confused:

BrandonParker
June 30th, 2002, 01:18 AM
Basically delegates are function pointers. However, this is an extreamly simplified view since they are actually objects.


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

using System;

namespace BrandonParekr
{

delegate double DoubleOp(double x);

class MainEntryPoint
{

static void Main(string[] args)
{
DoubleOp [] operations =
{
new DoubleOp(MathOperations.MulitiplyByTwo),
new DoubleOp(MathOperations.Square)
};

for(int i=0; i < operations.Length ; i++)
{
Process(operations[i],2.0);
Process(operations[i],7.94);
Process(operations[i],1.141);
}
}
static void Process(DoubleOp action,double value)
{
double result = action(value);
Console.WriteLine("Value is { 0 }, result of operation is { 1 }",
value, result);
}

}
}