Anonymous methods behave like regular methods except that they are unnamed. Anonymous Methods were introduced as an alternative to defining delegates that did very simple tasks, where full-blown methods amounted to more than just extra typing. Anonymous methods also evolved further into Lambda Expressions, which are even shorter methods.
What is Anonymous Methods?
An anonymous method is like a regular method but uses the delegate keyword, and doesn’t require a name, parameters, or return type. Following code example shows a regular method (used as a delegate for the CancelKeyPress event, Ctrl+C in a console application) and an anonymous delegate that performs the same role.
class Program
{
static void Main(string[] args)
{
// ctrl+c
Console.CancelKeyPress += new ConsoleCancelEventHandler
(Console_CancelKeyPress);
// anonymous cancel delegate
Console.CancelKeyPress +=
delegate
{
Console.WriteLine(“Anonymous Cancel pressed”);
};
Console.ReadLine();
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine(“Cancel pressed”);
}
}
The regular method which is uses as delegate is named ConsoleCancelEventHandler. The second statement that begins with the Console.CancelKeyPress += delegate demonstrates an anonymous method (delegate) that is equivalent to the longer form of the method. The point of notice is that because the parameters in the delegate aren’t used, they are omitted from the anonymous delegate. You have the option of using the parameter types and names if they are needed in the delegate.
Understanding Anonymous Generic Methods:
Delegates are really just methods as they are mostly used as event handlers. Generic methods are those that have parameterized types. (You can think about replaceable data types.) Therefore, anonymous generic delegates are anonymous methods that are associated with replaceable parameterized types. A very useful type is Func<t>. This generic delegate is defined in the System namespace and can be assigned to delegates and anonymous delegates with varying return types and parameters, which makes it a very flexible and useful.
Let’s take an example to understand that how we can use Anonymous Generic methods, following are simple example for Anonymous Generic Methods
class Program
{
static void Main(string[] args)
{
System.Func<long, long> Factorial =
delegate(long n)
{
if(n==1) return 1;
long result=1;
for(int i=2; i<=n; i++)
result *= i;
return result;
};
Console.WriteLine(Factorial(6));
Console.ReadLine();
}
}
For all intents and purposes, Factorial is a nested function. above code used Func<long,long>, where the first long parameter represents the return type and the second is the parameter. Notice that the listing also used a named parameter for the anonymous delegate.
Understanding Lambda Expressions in C#
A Lambda Expression is a concise delegate. The left side (of the =>) represents the arguments to the function and the right side is the function body. In below listed example, the Lambda Expression is assigned to the delegate FunctionPointer, but .NET 3.5 defines anonymous delegates like Action<t> and Func<t>, which can be used instead of the more formal, longer delegate statement. This means that you don’t have to define the delegate statement in below example.
class Program
{
delegate void FunctionPointer(string str);
static void Main(string[] args)
{
FunctionPointer fp =
s => Console.WriteLine(s);
fp("Dot Net Stuff!");
Console.ReadLine();
}
}
Following is an example shows the revision of above example, replacing the delegate statement with the generic Action<t> delegate type.
class Program
{
static void Main(string[] args)
{
System.Action<string> fp =
s => Console.WriteLine(s);
fp("Dot Net Stuff!");
Console.ReadLine();
}
}
Lambda Expressions we can define automatic properties. The basic idea behind automatic properties is that many times, programmers define properties that are just wrappers for fields and nothing else happens. If there are no additional behaviors, automatic properties allow the compiler to add the field, getter, and setter.
Summary: Anonymous Methods and Lambda Expressions are very powerful and useful in c#. There are predefined Generic Delegates Func<t>, Predicate<t> and Action<t>, are very useful for programmers. We will understand these into a separate article. Anonymous Methods and Lambda Expressions are widely used with Linq. You can begin exploring how Lambda Expressions support LINQ queries by seeing how Lambda Expressions are used in extension methods such as Select<t>, Where<t>, or OrderBy<t>.