Partager via


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

 

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)

https://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; }

    }

}

Comments

  • Anonymous
    July 18, 2012
    great explanation . Simple to understand and yet informative. Thanks  

  • Anonymous
    August 27, 2012
    Nice one , no doubt for novice like me.

  • Anonymous
    November 16, 2013
    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.

  • Anonymous
    December 04, 2013
    Thanks. Helped me understanding. :)

  • Anonymous
    February 12, 2014
    Superb Explanation. Thumbs up for this one..!!

  • Anonymous
    April 08, 2014
    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?.

  • Anonymous
    April 08, 2014
    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?

  • Anonymous
    April 25, 2014
    Very Nice and Easily understandable. Thanks

  • Anonymous
    September 07, 2014
    thank you very much Michael for this post ... very useful and easy to understand

  • Anonymous
    September 23, 2014
    Thanks for such a simple and useful explanation.

  • Anonymous
    November 04, 2014
    Check the extension method, www.negablog.com/.../create-custom-extension-method-in-c.html

  • Anonymous
    November 21, 2014
    Nice and Clear explanation in a precise Manner

  • Anonymous
    February 01, 2015
    Excellent way of explaining in simple terms thank you very much.

  • Anonymous
    April 26, 2015
    Best Example Ever on Extension method. Thanks Michael.

  • Anonymous
    April 26, 2015
    nice <a href="htt://www.grandindia.in"> greatindia </a>

  • Anonymous
    May 27, 2015
    very good explanation and made easy to understand.

  • Anonymous
    January 11, 2016
    Many thanks! I could finally understand in a simple way how does it work.

  • Anonymous
    January 31, 2016
    www.codingsack.com/.../bunch-of-useful-extension-methods

  • Anonymous
    January 31, 2016
    Here i have written some use full extension methods. www.codingsack.com/.../bunch-of-useful-extension-methods