// This "DoMath" delegate can point to ANY method that:
// - Returns an int
// - Accepts two ints as parameters
public delegate int DoMath(int x, int y);
private void button1_Click(object sender, EventArgs e)
{
int result;
DoMath a = new DoMath(Add);
result = a(3, 4);
MessageBox.Show(Convert.ToString(result));
UseDelegate(a);
}
public void UseDelegate(DoMath x)
{
int r = x(6, 6);
MessageBox.Show(Convert.ToString(r));
}
//This method can be pointed to by the DoMath delegate
public int Add(int x, int y)
{
return x+y;
}
//This method can be pointed to by the DoMath delegate
public int Subtract(int x, int y)
{
return x - y;
}
//This method can NOT be pointed to by the DoMath delegate
//because it has a different signature (only one argument)
public string Test(string y)
{
return "Test method";
}
}
BidVertiser
Showing posts with label C# Delegate. Show all posts
Showing posts with label C# Delegate. Show all posts
Wednesday, December 15, 2010
Tuesday, October 12, 2010
C# Delegate
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.
A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. If you have a delegate object and an appropriate set of arguments, you can invoke the delegate with the arguments.
An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
Subscribe to:
Posts (Atom)