New Methods for Old Classes in C#

After a hiatus of some years, I’m again working with C#.   Back then, I liked the language fine — it seemed like a somewhat improved Java.  Now I find it has undergone some wonderful changes. In particular, Extension Methods just wow me.

With Extension Methods, you can “lash on” method definitions to an existing class without recompiling the original and without extending the class or otherwise changing the class hierarchy.  You can even apply this feature to existing classes, such as Int32.

I believe that Ruby and JavaScript support adding new methods to classes and instances, but C# gives you this flexibility and strong typing, too.

Probably the best known example of Extension Methods is in the System.Linq namespace. Including this  namespace in a program allows the use of various aggregate, filter, and search functions (e.g., Average, Distinct,  ExceptFirst) on enumerable types such as arrays and lists.

Another use for Extension Methods might be support methods for frameworks.  This might allow POCOs –  Plain Ol’ CLR Objects – be used in frameworks, without requiring any change to the definition. This also keeps the original class free of functions that aren’t directly related to its concerns.

I’ve created a short and simple GitHub project, ClassyExtensions, that demonstrates how Extension Methods can be implemented.  Below is code for a very simple POCO, Foo:

using System;
namespace MyPocos
{
    public class Foo 
    {
        public Foo(Int32 num)
        {
            FooNum = num;
        }
        public Int32 FooNum { get; set; }
    }
} 

 

The extension code is in a separate library and namespace:

using System;
using MyPocos;
namespace MyExtensions
{
    public static class RandomClassName
    {
        public static Int32 PlusOne(this Foo foo)
        {    
            return foo.FooNum + 1;
        }
        public static Int32 PlusOne(this Int32 n)
        {
            return n + 1;
        }
    }
}

 

Finally, a console app that executes the extensions on instances of Foo and Int32:

using System;
using MyExtensions;
using MyPocos;

namespace MyMain
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // The definition of class Foo, its c'tor, and member FooNum come from MyPocos.
            // MyExtensions adds method PlusOne.  If that namespace is not included,
            // this code will not compile.

            Foo foo42 = new Foo(42);
            Foo foo99 = new Foo(99);

            Console.WriteLine($"FooNum of foo42 is {foo42.FooNum}, PlusOne is {foo42.PlusOne()}");
            Console.WriteLine($"FooNum of foo99 is {foo99.FooNum}, PlusOne is {foo99.PlusOne()}");

            // A user can create extensions for System classes.
            Console.WriteLine($"PlusOne of 0 is {0.PlusOne()}, PlusOne of 31415 is {31415.PlusOne()}");
        }
    }
}

Console output from the program is:

FooNum of foo42 is 42, PlusOne is 43
FooNum of foo99 is 99, PlusOne is 100
PlusOne of 0 is 1, PlusOne of 31415 is 31416

A method added to my class, another method added to Int32. Zowie!

Advertisements

One thought on “New Methods for Old Classes in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s