Rajendra Tripathy
Extension methods ??
By Rajendra Tripathy in .NET on Aug 08 2014
  • Rajendra Tripathy
    Aug, 2014 8

    Definition : An extension method has simplified calling syntax. It represents static methods as instance methods. An extension method uses the this-keyword in its parameter list. It must be located in a static class.Example ::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 Products = new List() { 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 :foreach (Product p in Products) { Console.WriteLine("{0} costs {1} (VAT: {2})", p.ProductName, p.ProductPrice, p.CalculateVat()); }

    • 1


Most Popular Job Functions


MOST LIKED QUESTIONS