Anonymous methods :

May 11, 2011
  • Anonymous methods allow you to define a code block where a "delegate" object is acceptable.
  • An anonymous methods use the keyword "delegate", instead of name of the method. This is followed by the body of the method.
  • Anonymous method always start with the keyword "delegate" and which is followed by parameters to be used inside the method & the method body itself.
  • You can reduce the code by preventing instantiation of the delegate and registering delegate with the methods.
  • It increases the maintainability & readability of our code by keeping the caller of the method & the method itself as close as possible to one another.
public MyForm() { Button btnSayHello = new Button(); btnSayHello.Text = "Hello"; btnSayHello.Click += delegate { MessageBox.Show("Hello!! User"); }; Controls.Add(btnSayHello); }

Note:

  • Anonymous methods are an easy or simplified way for you to assign handlers to the events. They take less effort as compared to delegates & are closer to the events they are associated with.
  • An anonymous methods can't access the out or ref parameters of an outer scope.
  • The anonymous-method-block can not access Unsafe code within it
  • Method attributes can't be applied to Anonymous methods. Also an anonymous methods can be added to the invocation list for delegates, but it can be only deleted from the invocation list if they have been saved to the delegates.