There’s an exciting new language feature in C# 3.0 that let’s us bring some tastes of dynamic languages into our statically typed world…
Type Extension Methods - static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods.
I released some source code over on Google Code that demonstrates the capabilities (requires Visual Studio 2008 (or Express)).
svn co http://developstuff.googlecode.com/svn/extensions
Check out what you can do (note, include the dll that I built and you can have these for free):
// DaysAgo, MinutesAgo, YearsAgo, SecondsAgo
DateTime daysAgo = 10.DaysAgo();
// ToHumanReadableString
Assert.Equal("10 days ago", daysAgo.ToHumanReadableString() );
// Within (range testing for ints and decimals)
Assert.True( 16.Within(15, 17) );
// Null checking without doing if(thing == null)
object o = null;
Assert.True( o.IsNull() );
Assert.False( o.IsNotNull() );
// String Conversions
Assert.Equal( 5.5M, "5.5".ToDecimal() );
Assert.Equal( 5, "5".ToInt() );
Assert.Equal( new DateTime(1981, 2, 18), "2/18/1981".ToDateTime() );
Assert.Equal( new DateTime(1981, 2, 18), "2/18/1981 00:00:00".ToDateTime() );
Assert.Equal( new DateTime(1981, 2, 18), "February 18, 1981".ToDateTime() );
// String Ranges
string longString = "This is a long enough string to test.";
Assert.Equal( "This", longString.First(4) );
Assert.Equal( "est.", longString.Last(4) );
Assert.Equal( " is a long enough string to test.", longString.From(4) );
// String sentences
int[] ints = new int[3] { 1, 2, 3 };
Assert.Equal( "1, 2, and 3", ints.ToSentence() );
Interesting huh? That’s just the beginning, I’ll probably be adding methods to these all the time, so check back in for more updates.
(And yes, I know that these are in Ruby / Rails… but we can have our fun too!)
Technically, you’re not extending the type with new methods. Extension methods are just static methods with attribute goodness so the IDE makes it look like it’s on your type, but it really isn’t. They’re definitely useful, though :)