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”;

//etc….
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):

[Test]
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.


Check out my latest book, the essential, in-depth guide to performance for all .NET developers:

Writing High-Performance.NET Code, 2nd Edition by Ben Watson. Available for pre-order: