Daily Archives: August 7, 2006

Checking all values of an enumeration in C#

I have a utility function that takes in a status enumeration and returns a string description associated with the given status code.

It looks something like this:

internal static string MailProcessCodeToString(MailProcessCodes eCode)
switch (eCode)
case MailProcessCodes.mpcGoodData:
    return “No errors detected in the order mail”;case MailProcessCodes.mpcNoHeader:
    return “Could not find header in order mail”;

I wanted to create a unit test that ensure there was an error message for every possible value of the eCode. Rather than write a separate unit test for each value (there are over 30–don’t ask).It’s fairly easy to do in .Net (using NUnit):

public void MailProcessCodeToString_AllSuccess()
int[] vals = (int[])Enum.GetValues(typeof(MailProcessCodes));
foreach (int val in vals)
string errorString = Utils.MailProcessCodeToString((MailProcessCodes)val);       

        string msg = string.Format(“{0} has no error string defined”,
Enum.GetName(typeof(MailProcessCodes), val));        Assert.IsTrue(errorString.Length > 0, msg);

Enum.GetValues() returns an array of all defined values for an enum, and Enum.GetName() translates a value into the name of the constant.

Now I have a unit  test which will tell me which error code does not have a corresponding string.