Extending Classes the Easy Way

I don’t think I’ve ever talked about Extension Methods, and I totally use them all the time! Here’s a quick overview.

Extension methods are a quick and easy way to add methods to a class you don’t otherwise have access to modify. An example would be any of the .Net classes, or external libraries that we use in code. Here’s how they look in code:

1
2
3
4
5
6
7
8
9
public static class ExtensionClass
{
    public static ReturnValue NewMethodName(
      this ObjectWereExtending variableName, int extraParamter,
      string extraParameter)
    {
        //method body
    }
}

So basically, you create a static class, and inside it you declare methods that have that special “this Object object” as the first parameter, and you’re good to go. Here’s a few examples from our code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//adding a range of objects to a ObservableCollection
//normally you can only add one at a time
public static void AddRange(this ObservableCollection collection,
  IEnumerable toAdd)
{
  foreach (T item in toAdd)
  {
      collection.Add(item);
  }
}

//adding a null sql parameter to a command
//if you add null using addwithvalue, 
//it doesn't actually send the parameter
public static void AddWithValue(this SqlCommand cmd,
  string parameterName, object value, SqlDbType type)
{
    cmd.Parameters.Add(new SqlParameter(parameterName, type, 0,
      ParameterDirection.Input, true, 0, 0, string.Empty,
      DataRowVersion.Current, value));
}

//add serialization support to any IFormatter class
public static byte[] Serialize(this IFormatter formatter, object graph)
{
  using (MemoryStream stream = new MemoryStream())
  {
      formatter.Serialize(stream, graph);

      byte[] buffer = stream.GetBuffer();

      if (buffer.Length == stream.Length)
          return buffer;
      else
          return stream.ToArray();
  }
}

//same with deserialization
public static T Deserialize(this IFormatter formatter, byte[] data)
{
  using (MemoryStream stream = new MemoryStream(data))
      return (T)formatter.Deserialize(stream);
}

public static T Deserialize(this IFormatter formatter, Stream stream)
{
  return (T)formatter.Deserialize(stream);
}

//see if a string has only alphanumeric characters
public static bool IsAlphaNumeric(this string str)
{
  return !System.Text.RegularExpressions.Regex.IsMatch(str,
      @"[^a-zA-Z0-9]");           
}

And so on. You can see how extension methods can be really handy To use them after they’re created, you just need a reference to the assembly they’re in, and make sure you have the imports / using statement at the top – VS doesn’t know how to resolve missing references for Extension methods, since as far as it’s concerned that method doesn’t exist until you reference the assembly. Unless they fixed that in VS2010.

Comments