Saturday, March 09, 2013

Extension Methods

Extensions methods allows you to add methods to an existing classes without modifying or inheriting it.

 

Previously we were adding static methods outside the class and calling it by passing the object as a parameter.

 

using System;

class Program {
    static void Main(string[] args) {
        var emp = new Employee() { Id = 1, Name = "John" };
        SampleExtensions.Print(emp);
    }
}

public class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class SampleExtensions {
    public static void Print(Employee emp) {
        Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
    }
}

 

We can upgrade this code using Extension methods. All we need is to

  • Create a static class
  • Add static method
  • Add this prefix before the first parameter declaration

 

Note: Extension methods only works with reference types

 

using System;

class Program {
    static void Main(string[] args) {
        var emp = new Employee() { Id = 1, Name = "John" };
        emp.Print();
    }
}

public class Employee {
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class SampleExtensions {
    public static void Print(this Employee emp) {
        Console.WriteLine("Employee: " + emp.Id.ToString() + "-" + emp.Name.ToString());
    }
}

This in fact, improves the readability of the code, so it is easy to understand.

No comments:

Post a Comment