09 September 2015

Extension Methods in C#.Net


  • Extension methods are a new feature in C# 3.0

  • You can use extension methods to extend a class/interface, but not to override them.

  • Extension methods are static methods of a static class, and the 1st parameter is preceded by the “this” modifier (refers to class/interface/the called value), 2nd onward parameters act as passing parameters as in normal method calling

  • you need to add the "using System.Linq" directive to the top of the code

  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code

  • If the class is sealed than there in no concept of extending its functionality

  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design

  • An extension method must be defined in a top-level static class

  • An extension method is defined as static method but it is called like as instance method

  • Overuse of extension methods is not a good style of programming


Ex: With Multiple Parameters
public static class MyExtensions
{
static int WordCount(this String str, char[] charArray)
{
return str.Split(charArray).Length;
}
}

And it can be called from an application by using this syntax:
string str = "Hello Extension Methods";
int i = str.WordCount(new char[] { ' ', '.', '?' });

Extension methods at compile time:


An extension method with the same name and signature in an interface or class method (1st priority) will never be called.


Inherit the class and then implement the functionality in an instance method in the derived class.


Use aggregation instead of inheritance.

Aggregation example:

university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.


Ex1: with Interface
public interface IMyInterface
{
        // Any class that implements IMyInterface must define a method 
        // that matches the following signature. 
        void MethodB();
}

public static class Extension
{
    public static void MethodA(this IMyInterface myInterface, int i)
    {
       Console.WriteLine("Extension.MethodA");
    }
}

public class A : IMyInterface
{
      public void MethodB() { Console.WriteLine("A.MethodB()"); }
}

class ExtMethodDemo
{
static void Main(string[] args)
{
A a = new A();
a.MethodA(1); //A contains no MethodA,
//so it calls the extension method that has a matching signature.
}
}

Output:
    Extension.MethodA

Ex2: with class
public class Class1
    {
        public string Display()
        {
            return ("Display");
        }

        public string Print()
        {
            return ("Print");
        }
    }

public static class XX
    {
         public static void NewMethod(this Class1 ob)
        {
            Console.WriteLine("NewMethod");
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            Class1 ob = new Class1();
            ob.Display();
            ob.Print();
            ob.NewMethod();
            Console.ReadKey();
        }
    }
}

Output:
Display
Print
NewMethod

The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.


One of the great reasons for Extension methods is behind LINQ. Without extension methods a lot of what you can do in LINQ would be very hard. The Where(), Contains(), Select extension methods means a lot more functionality is added to existing types without changing their structure


The biggest disadvantage is that there's no compiler error or warning if you have a regular method and an extension method with the same signature in the same context.


Extension methods fit very well into an OOP design: consider the simple method



bool empty = String.IsNullOrEmpty (myString)

in comparison to
bool empty = myString.IsNullOrEmpty ();

Ex3: With Multiple parameters in Extension Method
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);
}
}

public class Product
{
public string ProductName { get; set; }
public double ProductPrice { get; set; }
}

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, And it can be done by using EXTENSION METHODS.

No comments: