Thursday, November 12, 2009

Anonymous method

  • Anonymous method
- Its a .net 2.0 feature
-We can create nameless methods, which can be called using delegates
  • Why Anonymous methods?
 In some cases we are forced to create a class or method just for the sake of using delegates. We can avoid it using anonymous method.


Real time example:

  • Button click event implementation in windows form is handled using anonymous method:

            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(38, 116);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            //this.button1.Click += new System.EventHandler(this.button1_Click);

            this.button1.Click += delegate(object sender, System.EventArgs e)
            {
                System.Windows.Forms.MessageBox.Show("Invoked using anonymous method!!"); 
            };

No comments: