Fun with extension methods or don’t envy Visual Basic

We all like the ToString() method conveniently located in every class. But unfortunately there is no ToInt() method where you need it most. We are not completely out of luck however thanks to a new feature in c# called extension methods. The extension methods are simply static methods that behave like if they were from another class. “Why not just extend the actual class?” someone might ask. Well, sometimes we just can’t do that and other times it is just plain inconvenient, imagine changing every string in out program to be from a type MyString…

So let’s create our ToInt() method that will extend the string class:

public static class Extensions
{
    public static int ToInt(this string s)
    {
        return Int32.Parse(s);
    }
}

[TestMethod()]
public void ToIntTest()
{
    Assert.AreEqual(123, "123".ToInt());
}

A little bit weird syntax but nothing that we can’t live with. Now each time we have a string that is composed of digits we can easily convert it to a number.

Another two methods that I love from Visual Basic are Left(i) and Right(i):

public static string Left(this string s, int length)
{
    return s.Substring(0, length);
}

public static string Right(this string s, int length)
{
    return s.Substring(s.Length - length);
}

[TestMethod()]
public void LeftRightTest()
{
    Assert.AreEqual("AB", "ABCD".Left(2));
    Assert.AreEqual("CD", "ABCD".Right(2));
}

Notice that the first parameter with the keyword this is the class that we are extending and the next parameter(s) are the parameters of the method. I really can’t imagine what they (Anders?) were thinking when they came up with this syntax but one can get used to it I guess…

One last thing… Visual Basic has this nice inline xml syntax that c# does not have:

Dim xml = <tag></tag>

So I was thinking…

public static XElement ToXml(this string s)
{
    return XElement.Parse(s);
}

[TestMethod()]
public void ToXmlTest()
{
    var xml = @"<tag></tag>".ToXml();
    Assert.AreEqual("tag", xml.Root.Name);
}

Here is a link to the MSDN article describing the extension methods in greater detail.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s