Anonymous methods

C# 2.0 introduced anonymous methods, while C# 3.0 introduced Lambda expressions, which were later replaced with anonymous methods.

One case where anonymous methods provide functionality that isn't possible when using a Lambda expression is that they allow us to avoid parameters. These allow anonymous methods to be converted into delegates with a number of different signatures.

Let's look at an example of how to use anonymous methods to initiate a delegate:

public void InvokeDelegatebyAnonymousFunction()
{
//Named Method
StringDelegate StringDel = HelperClass.StringMethod;
StringDel("Chapter 5");

//Anonymous method
StringDelegate StringDelB = delegate (string s) { Console.WriteLine(s); };
StringDelB("Chapter 5- Anonymous method invocation");

}
internal class HelperClass
{
public void InstanceMethod()
{
System.Console.WriteLine("Instance method Invoked.");
}

public static void StaticMethod()
{
System.Console.WriteLine("Invoked function Static Method.");
}

public static void StringMethod(string s)
{
Console.WriteLine(s);
}
}

//Output:
Chapter 5
Chapter 5- Anonymous method invocation

In the preceding code, we defined a string delegate and wrote some inline code to invoke it. The following is the code where we defined the inline delegate, also known as an anonymous method:

StringDelegate StringDelB = delegate (string s) { Console.WriteLine(s); };

The following code shows how we can create an anonymous method:

// Creating a handler for a click event.
sampleButton.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show(
"Sample Button Clicked!"); };

Here, we created a code block and passed it as a delegate parameter.

An anonymous method will throw an error if the runtime encounters any jump statements, such as goto, break, or continue, inside the code block and the target is outside the code block. Also, in a scenario where a jump statement is outside the code block and the target is in it, with the int anonymous method, an exception will be thrown.

Any local variables that are created outside of the delegate's scope and contained in an anonymous method declaration are called outer variables of the anonymous method. For example, in the following code segment, n is an outer variable:

int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };

Anonymous methods are not allowed on the left-hand side of the is operator. No unsafe code can be accessed or used in an anonymous method, including the in, ref, or out parameters of an outer scope.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.19.75