harriyott.com

Friday, June 20, 2008

Extension methods in C#

I recently needed to encrypt a string with MD5 encryption. Not having used this before, I looked at the MSDN page for the MD5 class. There was a ComputeHash method, but no overload took a string parameter - just a stream or a byte array.

I may be naive, but I would have thought encrypting a string would be a common enough task to warrant its own overload, but apparently not. It is common enough though, for some example code that converts the string to a byte array, calls ComputeHash, and converts the result to a hex string. This example seems to work fine, so I don't know why it isn't just squished into the class in the framework.

Not wanting to just add this example to the class I was working on, I thought I would write my first ever extension method, and add the example as an overload to the MD5 framework class. I read about extension methods in the marvelous Pro C# 2008 and the .NET 3.5 Plaform, which are straightforward, but the syntax is a little unintuitive:

public static class MD5Extensions
{
public static string ComputeHash(this MD5 md5, string input)
{
byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
}


In short, both the class and the method should be defined as static, and the first parameter has "this" before the type, which is the class that is being extended. I'm going to have to keep looking this up, as there are three things to remember. I would have preferred a new keyword, extended, which works in the same way as partial classes, like so:
public extended class MD5
{
public string ComputeHash(string input)
{
...
}
}


This would have been far easier to remember, and would actually look like the programmer's intention. I'm sure there must be a good reason for the way it has been done though.

2 Comments:

Anonymous Oliver Sturm said...

I guess one of the reasons may be that you can use extension methods with all sorts of types, not just actual classes. The type of the first parameter specifies it, and it can be "non-class" stuff, like "int" or even IEnumerable<T>.

June 20, 2008 9:37 PM  
Anonymous Simon said...

Thanks Oliver, that explains it. I knew there must have been a good reason!

June 20, 2008 10:00 PM  

Post a Comment

Links to this post:

Create a Link

<< Home