Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Anonymous methods in C#?

What is anonymous method in C#?

A method without a name is called as an anonymous method is, the delegate operator creates an anonymous method that can be converted to a delegate type.

What is use of anonymous methods in C#?

  • You can use an anonymous method to create an anonymous function with unnamed inline code.
  • C# 2.0 introduced the concept of anonymous methods to write unnamed inline statement blocks that can be executed in a delegate invocation.

How to create and use anonymous method?

An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.

Code example

//declare delegate
delegate void displayFullName(string fname, string mName, string lName);
 
//instantiate delegate with anonymous method
displayFullName fullName = delegate (string fname, string mName, string lName) {
    Console.WriteLine("Full name: " + fname + " " + mName + " " + lName);
   };


 
//anonymous method with generic action delegate
Action<string, stringstring> userFullName = delegate (string fname, string mName, string lName)
{
  Console.WriteLine("User full name: " + fname + " " + mName + " " + lName);
}; 

Invalid entry,please enter valid data.

Loading