Home > DeveloperSection > Articles > Extension Method

Extension Method


.NET .NET 
Ratings:
1 Comment(s)
 4052  View(s)
Rate this:

Extension Methods in C#


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.

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

        }


Thanks..

By Sushant Mishra on   2 days ago

It was really helpful to read this post.


Don't want to miss updates? Please click the below button!

Follow MindStick