Anonymous Method in C#

Anonymous Method in C#

Anonymous methods are “name-less methods”, that can be invoked by using the delegate variable or an event.

Event with Anonymous Method:

EventName += delegate(param1, param2, …)
{
//method body here
}

Anonymous methods can be used anywhere within the method, to create methods instantly, without define a method at the class level.

Guidelines:

  1. It can’t be called without a delegate or event.
  2. It can’t contain jump statements like go to, break, continue.
  3. It can access local variables and parameters of outer method.
  4. It can be passed as a parameter to any method; in this case, the delegate acts as data type for the anonymous method.
  5. It can’t access ref or out parameter of an outer method.
  6. It is mainly used for event handlers.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply