How will you make it if you never even try?

April 2, 2009

Example where calling Extension Methods on null references is useful: Parameter Validation

Filed under: C# — Tags: , , , , , — charlieflowers @ 2:56 am

In a recent post, I pointed out that extension methods can be called on null references. For example, this works perfectly fine:

public static void PrintToConsole(this string self)
   if(self != null)
      Console.WriteLine("The string is: " + self);
      Console.WriteLine("The string is NULL.");

// Elsewhere in the code
string myString = null;

I said I’d give some examples of where this would actually be useful (not just a gimmick as it might appear on first blush).

One such case is parameter validation. Rick Brewster has come up with a fantastic approach for parameter validation, which lets your code look something like this:

public static void Copy(T[] dst, long dstOffset, T[] src, long srcOffset, long length)
     .IsNotNull(dst, “dst”)
     .IsNotNull(src, “src”)
     .IsIndexInRange(dst, dstOffset, “dstOffset”)
     .IsIndexInRange(dst, dstOffset + length, “dstOffset + length”)
     .IsIndexInRange(src, srcOffset, “srcOffset”)
     .IsIndexInRange(src, srcOffset + length, “srcOffset + length”)
     // Further code snipped.

No doubt that’s beautiful syntax. But one of Rick’s main goals was this: Incur the least possible overhead if the parameters are all correct. In particular, don’t instantiate any additional objects if the parameters are correct.

And the way this is achieved depends on the fact that extension methods can be called on null references. If all the parameters are OK, the Begin() method, the IsNotNull() method, and so on, all return null. However, they still have a return type, and that return type has extension methods on it called “Begin”, “IsNotNull”, “IsPositive” and so forth.

You can learn more about Rick’s approach here and here.

C# Delights: Extension methods can be called on null references (and that’s extremely useful)

Filed under: C# — Tags: , , , — charlieflowers @ 12:42 am

Did you know that C# extension methods can be called on null references?? Yes, they can. For example, the following method …

public static void PrintToConsole(this string self)
   if(self != null)
      Console.WriteLine("The string is: " + self);
      Console.WriteLine("The string is NULL.");

… can be called as follows:

string someString = null;


The output would be:
The string is NULL.

Is this just a gimmick? You might think so at first blush, but it is actually remarkably useful. I’ll write another post soon giving some examples of when it is useful. Here’s one hint: imagine a case where you don’t want the overhead of instantiating objects unless you’re in an unusual situation. (OK, here’s another hint … what if you want to write code that applies business logic to non-null values, but seamlessly ignores nulls, so that the code doesn’t have to be all cluttered up with null checks).

April 1, 2009

C# Delights: You can put Extension Methods onto Enums!

Filed under: C# — Tags: , , , , — charlieflowers @ 8:04 am

Often, you need to associate other information with the members of an Enum. For example, say you have the following enum:

public enum DaysOfWeek : int
   Sunday = 1,
   Monday = 2,
   Tuesday = 3,
   Wednesday = 4,
   Thursday = 5,
   Friday = 6,
   Saturday = 7

That’s all well and good. But say you need to associate additional information with each enum member. For example, say your legacy database represents the days of the week with the following 2 letter codes: “Sn”, “Mo”, “Te”, “Wn”, “Tr”, “Fi”, “St”. Notice I picked codes that are not intuitive and are not always the first 2 characters. Crazy, but we all know legacy databases can be crazy.

Also, let’s imagine that your company needs to associate a decimal hourly rate with each day, representing the fact that you charge different rates for different days.

C# has a very nice, new way you can do this. Before C# 3.0, the best way I knew of to handle this was to not use an Enum at all. Rather, I would make a class that was much like a singleton, but with more than one instance. It would have a private constructor, so that no other classes outside of it could make instances of it. However, it would expose static properties with the exact set of instances that were allowed (7 in our case, and the properties would be named “Sunday”, “Monday”, etc.). Each instance would have properties for “DatabaseCode”, “Name” and “HourlyRate”. That’s not bad, but the new way is better in many cases.

The new way is this: You can place extension methods onto Enums! So, in our case, we would do the following:

public static class DaysOfWeekExtensions
   private static string[] databaseCodes = new string[] { "Sn", "Mo", "Te",
      "Wn", "Tr", "Fi", "St" };

   private static decimal[] rates = new decimal[] { 2.5m, 3.6m, 0m, 1.2m,
      8.8m, 42m, 3.6m };

   public static string DatabaseCode(this DaysOfWeek self)
      int index = (int)self - 1;
      return databaseCodes[index];

   public static decimal HourlyRate(this DaysOfWeek self)
       int index = (int)self - 1;
       return rates[index];

And then you’d use it like this:

Console.WriteLine("For Tuesday, the database code is " + 
   DaysOfWeek.Tuesday.DatabaseCode() + " and we charge " +
   DaysOfWeek.Tuesday.HourlyRate() + ".");

Click here for another example.

Create a free website or blog at