rulururu

post Love or Hate Extension Methods?

July 14th, 2008

Filed under: .NET — Kai @ 12:39 pm

In C#, there is no String.Left() function. Fair enough; we can roll up our sleeves and write our own function lickety-split:

public static string Left(string s, int len)
{
    if (len == 0 || s.Length == 0)
        return "";
    else if (s.Length <= len)
        return s;
    else
        return s.Substring(0, len);
}

And call it like so:

var s = "superlongstring";
s = Left(s, 5);

But with the advent of C# 3.0, there’s an even better way — extension methods. With an extension method, we “extend” the String to add the missing function. The code is fairly similar:

public static string Left(this string s, int len)
{
    if (len == 0 || s.Length == 0)
        return "";
    else if (s.Length <= len)
        return s;
    else
        return s.Substring(0, len);
}

And now we can call it as if this very method existed on the String class as shipped:

var s = "superlongstring";
s = s.Left(5);

Pretty slick. It’s difficult not to fall in love with extension methods, as they allow you to mold classes into exactly what you think they should be. This is fairly innocuous in C#, as extension methods only allow you to add new functionality to classes, not override, remove, or replace anything.

1 Comment »

  1. […] - bookmarked by 4 members originally found by cucar on 2009-01-20 Love or Hate Extension Methods? http://bka-bonn.de/wordpress/index.php/2008/07/14/love-or-hate-extension-methods/ - bookmarked by […]

    Pingback by Bookmarks about Extension — February 10, 2009 @ 12:15 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)