Ever since the first release of C#, functions have been considered citizens of the language. Already then we could declare a typed function signature to hold a pointer to any matching method :
public delegate int MyDelegate(int x, int y);
public static int MyMethod(int x, int y)
{
return x + y;
}
public static void Main(string[] args)
{
MyDelegate myDelegate = new MyDelegate(MyMethod);
int result = myDelegate(1, 2);
}
The second release of C# gave greater importance to functions. Methods could then be instantiated from code, like any other object type. Delegates were no more limited at pointing to class members, as they could then handle anonymous methods :
public delegate int MyDelegate(int x, int y);
public static void Main(string[] args)
{
MyDelegate myDelegate = delegate(int x, int y)
{
return x + y;
};
int result = myDelegate(1, 2);
}
The third release of the language introduced generic delegates, which eliminated the need to declare a delegate for every possible function signature. Furthermore, a new syntax was provided to create methods from code, namely the lambda expressions :
public static void Main(string[] args)
{
Func<int,int,int> myDelegate;
myDelegate = new Func<int,int,int>((x, y) => x + y);
int result = myDelegate(1, 2);
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment