Extension Methods in C#

Extension Methods in C#

December 12, 2011 3:20 pm 1 comment

Hi Folks,

Just heard about a concept called Extension methods in C# and decided to share that with you all.  As the name implies extension methods adds extra functionality to a class implementation which can’t be modified now. For example if you are using an API and you need to expand some existing functionality. Can you do it ? Yes. You can with Extension Methods.

Let’s learn with example.

Now let’s create a class called “Products” with “displayProduct()” method. Now let’s assume we don’t have control to change the above class modification but we need to add a “printProduct()” functionality to the existing products.

Our Basic Products Class

 public class Products
    {
        public string Name
        {
            get;
            set;
        }

        public void displayProduct()
        {
            //Display the product
            Console.WriteLine("Displaying the Product");
        }
    }

And this is how we implemented the new functionality.

public static class ProductExtension
    {
        public static void printProduct(this Products pro)
        {
            //Print Product
            Console.WriteLine("Printing the Product");
        }
    }

Create a static class and add “printProduct()” functionality as a static method.

Now you can access Display and Print functionality as always.

class Program
    {
        static void Main(string[] args)
        {
            Products MyProduct = new Products();
            MyProduct.displayProduct();
            MyProduct.printProduct();
            Console.Read();
        }
    }

C# Roxxxx.
Happy Coding :)

1 Comment

Leave a reply