How to create a simple Extension method. A simple example.

How to create a simple Extension method. A simple example.

  • Comments 10

 

I’ve been trying to get my head around Extension methods. And I finally got it.

 

Imagine for example the following scenario. You have an assembly created by someone else.

This assembly contains a class called Products, this class has a field for the ProductName and for the ProductPrice.

 

namespace Products

{

    public class Product

    {

        public string ProductName { get; set; }

        public double ProductPrice { get; set; }

    }

}

 

No problems so far, so you use this class in a list and display the name and price:

 

    class Program

    {

        static void Main(string[] args)

        {

            List<Product> Products = new List<Product>()

            {

                new Product{ProductName = "White Shoe", ProductPrice = 10},

                new Product{ProductName = "Green Shoe", ProductPrice = 5},

                new Product{ProductName = "Black Shoe", ProductPrice = 15}

            };

 

            foreach (Product p in Products)

            {

                Console.WriteLine("{0} costs {1}", p.ProductName, p.ProductPrice);

            }

        }

    }

 

Now you realize it would be great to display how much the VAT (tax) is of the price as well.

However, you do not own or have control over the Product class since it is owned by someone else. So you can’t add a CalculateVat() method to the product class.

You could of course, in code above, display it like so:

 

            foreach (Product p in Products)

            {

                Console.WriteLine("{0} costs {1} (VAT: {2})", p.ProductName, p.ProductPrice, (p.ProductPrice * .25));

            }

 

This however requires you to do it everywhere you display this, and if the VAT changes, you have to edit the value everywhere, so it would be much nicer

to have this as a method on the Product class directly instead. Enter the Extension method.

 

This is as simple as this, define a static class, declare a static method that does what you want to do. The method should take as an argument the class

we want to add the method to and it has to be prefixed with the THIS keyword. Like so:

 

    public static class MyExtensions

    {

        public static double CalculateVat(this Product p)

        {

            return (p.ProductPrice * .25);

        }

    }

 

That is all that is needed, we can now call the Extension method (it will be marked with a blue down arrow in Intellisense) on the Product instance, like so:

 

            foreach (Product p in Products)

            {

                Console.WriteLine("{0} costs {1} (VAT: {2})", p.ProductName, p.ProductPrice, p.CalculateVat());

            }

 

Full code is below.

More information here:

 

C# Programming Guide - Extension Methods (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/bb383977.aspx

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ExtensionMethod

{

    using Products;

 

    class Program

    {

        static void Main(string[] args)

        {

            List<Product> Products = new List<Product>()

            {

                new Product{ProductName = "White Shoe", ProductPrice = 10},

                new Product{ProductName = "Green Shoe", ProductPrice = 5},

                new Product{ProductName = "Black Shoe", ProductPrice = 15}

            };

 

            foreach (Product p in Products)

            {

                Console.WriteLine("{0} costs {1} (VAT: {2})", p.ProductName, p.ProductPrice, p.CalculateVat());

            }

        }

    }

 

    public static class MyExtensions

    {

        public static double CalculateVat(this Product p)

        {

            return (p.ProductPrice * .25);

        }

    }

}

 

namespace Products

{

    public class Product

    {

        public string ProductName { get; set; }

        public double ProductPrice { get; set; }

    }

}

Leave a Comment
  • Please add 3 and 7 and type the answer here:
  • Post
  • great explanation . Simple to understand and yet informative.

    Thanks  

  • Nice one , no doubt for novice like me.

  • Thank you for taking your valuable time to explain in simple language and clear example about Extension method. Thanks to your effort, I believe, I have understood what it is about.

  • Thanks. Helped me understanding. :)

  • Superb Explanation. Thumbs up for this one..!!

  • nice explanation,please clear the below doubt.

    we have created namespace products and product class with product name and product price.in other namespace where we added new method CalculateVat()

      public static double CalculateVat(this Product p)

           {

               return (p.ProductPrice * .25);

           }

    so istead of above method we can write a method to calculate the vat.

      public double CalculateVat()

           {

               Product p

               return (p.ProductPrice * .25);

           }

    and in the main() method.

    suppose product price is 100 rs.

    then we can write the below code

    Console.WriteLine("{0} costs {1} (VAT: {2})", p.ProductName, p.ProductPrice, CalculateVat(100));

    Note: we can create a new method in the class rather then adding method to existing type.

    please let me know you comments and explain me why we should use extension method?.

  • Namespace ExtensionMethod, you have added new method CalculateVat(Extension method) of Product type

    so my question : if i have cretaed new project ExtensionMethod and added the reference of previously created class Product

    so the new method CalculateVat(Extension method),will be avaliable in this ExtensionMethod namespace?

  • Very Nice and Easily understandable. Thanks

  • thank you very much Michael for this post ... very useful and easy to understand

  • Thanks for such a simple and useful explanation.

Page 1 of 1 (10 items)