I love Extension Methods

21 Apr
2009

Extension methods is one of the best things added to .NET.  It’s a great way to share code and helper method with other team members.  Traditionally developers would create Helper Classes or Utility Classes that can perform specific actions related to an object or domain.  The problem with this approach was that there wasn’t an easy way to discover that these helper or utility classes existed other than searching or asking.  Now with extension methods, these helper methods that are related to the specific object can be discovered simply with the uses of intellisense.  For example if you created an Extension Method on top of System.String, called ReverseString.  All you would have to do is type “myString.ReverseString()”. How easy is that!!

In this example, I’ll show you how to use Extension methods to transform one object to another.  This is a great way to centralize your transformation code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ExtensionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Butterfly butterfly = new Caterpillar().ToButterfly();
        }
    }
 
    public static class Extensions
    {
        public static Butterfly ToButterfly(this Caterpillar caterpillar)
        {
            return new Butterfly() { Name = caterpillar.Name };
        }
    }
 
    public class Caterpillar
    {
        public string Name { get; set; }
    }
 
    public class Butterfly
    {
        public string Name { get; set; }
    }
}

Comment Form

top