Alex Rivera | Logout

Lance Hunt's C# Coding Standards - enum confusion

Asked 2009-02-27T11:17:43.613
15

My team has recently started using Lance Hunt's C# Coding Standards document as a starting point for consolidating our coding standards.

There is one item that we just don't understand the point of, can anyone here shed any light on it?

The item is number 77:

Always validate an enumeration variable or parameter value before consuming it. They may contain any value that the underlying Enum type (default int) supports.

Example:

public void Test(BookCategory cat)
{
if (Enum.IsDefined(typeof(BookCategory), cat))
{…}
}
Edit
Report

1 Answer

14

I think the comments above pretty much answered the question. Essentially, when I wrote this rule I was trying to convey a defensive coding practice of validating all inputs. Enums are a special case because many developers incorrectly assume that they are validated, when they are not. As a result, you will often see if statements or switch statements fail for an undefined enum value.

Just keep in mind that by default an enum is nothing more than a wrapper around an INT, and validate it just as if it were an int.

For a more detailed discussion of proper enum usage, you might check out blog posts by Brad Abrams and Krzysztof Cwalina or their excellent book "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries"

answered 2009-02-27T17:35:18.840

Your Answer