in

Fort Worth .NET Users Group

jake

C# 3.0 Type Extensions

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<decimal>( 5.5M, "5.5".ToDecimal() );
Assert.Equal<int>( 5, "5".ToInt() );
Assert.Equal<datetime>( new DateTime(1981, 2, 18), "2/18/1981".ToDateTime() );
Assert.Equal<datetime>( new DateTime(1981, 2, 18), "2/18/1981 00:00:00".ToDateTime() );
Assert.Equal<datetime>( new DateTime(1981, 2, 18), "February 18, 1981".ToDateTime() );

// String Ranges
string longString = "This is a long enough string to test.";
Assert.Equal<string>( "This", longString.First(4) );
Assert.Equal<string>( "est.", longString.Last(4) );
Assert.Equal<string>( " is a long enough string to test.", longString.From(4) );

// String sentences
int[] ints = new int[3] { 1, 2, 3 };
Assert.Equal<string>( "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!)

Read the complete post at http://www.thoughtstoblog.com/articles/2008/1/23/c-3-0-type-extensions

Copyright FWDNUG 2008
Powered by Community Server (Commercial Edition), by Telligent Systems