20 August 2010

Extensions: Watch Your Step

I had one of those moments where I wonder if I'm really an expert-level C# programmer, and thought I'd share my embarrassing moment, to help other programmers who are new to extensions, are having the same problem, or for a good laugh.

I created the following C# extension, to safely handle conversion of an object that may contain DBNull to a string; because System.Object.ToString() throws an exception when the object is DBNull.

I spent the better part of 30 minutes trying to figure out why adding to my code did not implement the extension in a file containing several partial classes.  I'm sure you can spot the error:

using System;
namespace Company.Extensions.System_Object.ToSafeString {
 static partial class ToSafeStringExtension {
  public static string ToSafeString(this object obj) {
   if (obj is DBNull)
    return string.Empty;
   return obj.ToString();
  }
 }
}

You probably guessed that because I have been writing many partial classes, I habitually created ToSafeString as a static partial instead of public static!  The extension was not appearing in Intellisens, and was otherwise inaccessible, simply because the public access modifier was missing.  The class certainly can be declared as partial, but there is no reason to do so.

Here is the corrected code:

using System;
namespace Company.Extensions.System_Object.ToSafeString {
 public static class ToSafeStringExtension {
  public static string ToSafeString(this object obj) {
   if (obj is DBNull)
    return string.Empty;
   return obj.ToString();
  }
 }
}

No comments:

Post a Comment

Please provide details, when posting technical comments. If you find an error in sample code or have found bad information/misinformation in a post, please e-mail me details, so I can make corrections as quickly as possible.