May 18

More on extension methods

Posted in C#      Comments Off on More on extension methods

I’ve already posted about this topic in the past. However, it looks like there are still some people which don’t take full use of this new (ok, not so new anymore!") cool feature. In my opinion, extension methods are great and they end up simplifying (a lot) the code we need to write.

If you’ve been following this blog, I guess that there aren’t any doubts on my position regarding NH use (you should use it whenever you need a good ORM). Unfortunately, there will always be scenarios where you can’t really use it. For instance, in these last days I had to help some colleagues with adding some new features to legacy code (where the use of straight ADO.NET code was mandatory). This is the kind of scenario where extension methods really shine!

Here are a couple of simple methods that ended up making our life a lot easier:

public static class IDbCommandExtension {
    public static IDbCommand SetCommandText(this IDbCommand cmd, String text) {
        cmd.CommandText = text;
        return cmd;
    public static IDbCommand SetCommandType(this IDbCommand cmd, CommandType cmdType)  {
        cmd.CommandType = cmdType;
        return cmd;
    public static IDbCommand AddParameter(this IDbCommand cmd, String parameterName, Object value) {
        var parameter = cmd.CreateParameter();
        parameter.ParameterName = parameterName;
        parameter.Value = value;
        return cmd;

With these helpers, I can start writing code that looks like this:

var cmd = Connection.CreateCommand()

From this point on,it’s really straightforward: I’d get a reader or execute the command without any additional worries.

You can always say that the previous code breaks a couple of good OO recommendations(think CQS, for instance). However, and if it’s not obvious, I’m treating the previous code as infrastructure code. In these cases, I’m really in favor of breaking some good OO rules for having increased productivity.

Btw, I’m thinking of starting a C# 4.0 series. Anyone interested? (don’t worry: even if the answer is no, I’ll write about it anyway 😉 )