In Using Extension Methods in VS2008, I talked about how cool it might be to use Extension Methods as a way to add some handy functions directly to the string class. Here is the code for adding "ToUTCCodedTime" as an extended method to the string class using Extensions Methods which are now possible in .NET 3.5.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassLibrary1
{
public static class SharedCode
{
public static string ToUTCCodedTime(this string t)
{
// Method Extension Class
// Adds a new method to the string class
DateTime dt = System.DateTime.Parse(t).ToUniversalTime();
return dt.ToString("yyyyMMddHHmmss.0Z");
}
}
}
For the uninitiated, you start by creating a new Class Library and then pasting this code into it. I should also note here that the class must be a static class in order to contain Extension Methods. If you already have a class library that you're using to store common shared functions then you can just paste the body of the class in (the
public static string block...). To use the class, make sure each of your projects has a reference to the new class and that you have a valid
using directive for it. Once you do, you'll be able to take any string value and do this:
string strValue = strTime.ToUTCCodedTime;
IntelliSense will display this method using the extension method icon as shown below.
So that's it, you can create your own extension methods for practically any class (not just
string) by changing the reference
'this string t' to refer to the proper class type. So, '
this int t' should work for integers.