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).


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;
                return x *factorial(x - 1);

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


      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());

  Modified On Nov-29-2017 09:12:07 PM

Leave Comment