articles

Home / DeveloperSection / Articles / Extension Method

Extension Method

Anonymous User6017 22-Jul-2010

Extension method in C# provides a way to add our own method to class without inheriting it.

All we have to do to create extension method is to create our own static method and put ‘this’ keyword in front of first argument type of the method(the type that will be extended).

Example

Creating static method and using this keyword in front of int as it will be extended.

public static int factorial(this int x)
         {
            if (x<= 1)
                return 1;
            else if (x== 2)
                return 2;
            else
                return x *factorial(x - 1);
        }


now when we use int variable method it will be shown in list.


 Extension Method

 private void btnFact_Click(object sender, EventArgs e)
        {
            int i;
            i= Convert.ToInt32(txtNum.Text);           
//using factorial() method.
            MessageBox.Show("Factorial is: " + i.factorial().ToString());
        }

Extension Method


Updated 04-Mar-2020
I am a content writter !

Leave Comment

Comments

Liked By