An anonymous method is inline unnamed method in the code. It is created using the
delegate
keyword and doesn’t required name and return type.- class Program
- {
- //delegate for representing anonymous method
- delegate int del(int x, int y);
- static void Main(string[] args)
- {
- //anonymous method using delegate keyword
- del d1 = delegate(int x, int y) { return x * y; };
- int z1 = d1(2, 3);
- Console.WriteLine(z1);
- }
- }
- //output:
- 6
- Anonymous Method as an Event Handler
- protected void Page_Load(object sender, EventArgs e)
- {
- // Click Event handler using Regular method
- btnCancel.Click += new EventHandler(ClickEvent);
- // Click Event handler using Anonymous method
- btnSubmit.Click += delegate { lblmsg.Text="Submit Button clicked using Anonymous method"; };
- }
- protected void ClickEvent(object sender, EventArgs e)
- {
- lblmsg.Text="Cancel Button clicked using Regular method";
- }
- Key points about anonymous method
- A variable, declared outside the anonymous method can be accessed inside the anonymous method.
- A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
- We use anonymous method in event handling.
- An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
- Unsafe code can’t be accessed within an anonymous method.
- An anonymous method can’t access the ref or out parameters of an outer scope.
No comments:
Post a Comment