Friday, December 01, 2006

Adding Some Armor to Methods Using Passed Enums

In my previous post I demonstrated the fallibility of methods that take enumerations as parameters. As a defense you can use the Enum.IsDefined() method to check the validity of passed enum values:

static void SafeColorToString(EnumLegalColor color) {

if(!Enum.IsDefined(typeof(EnumLegalColor), color))
throw new Exception(string.Format("{0} is not a valid EnumLegalColor", (int) color));

Console.WriteLine(color.ToString());
}

Enumerations Aren't As Bullet Proof As I Thought

Pass an enumeration as a method parameter and its guaranteed to be valid right?
Wrong!

This code compiles and executes with no runtime error:
using System;

namespace Enumerating_Fun {

enum EnumLegalColor{red=1, white=2, blue=3};

class Program {

static void Main(string[] args) {

PrintColor(EnumLegalColor.red);
PrintColor(EnumLegalColor.white);
PrintColor(EnumLegalColor.blue);

PrintColor((EnumLegalColor) 1234);

while(!Console.KeyAvailable)
;
}


static void PrintColor(EnumLegalColor color) {

switch(color) {
case EnumLegalColor.red:
Console.WriteLine("Le Rouge");
break;

case EnumLegalColor.white:
Console.WriteLine("Le Blank");
break;

case EnumLegalColor.blue:
Console.WriteLine("Le Blu");
break;

default:
Console.WriteLine("WTF!");
break;
}
}
}
}

C# Sucks!

JK!! Seriously, though, somewhere around C#-3 we should have inculcated ourselves with the question: "Does 'CAN' == 'SHOULD...