Do not prefix enum values with type name (CA1712, Microsoft.Naming)

by Mark Zhou 28. November 2010 23:42

Many C/C++ merged C# developers is habitually to prefix the values for an enum with its type name, for example, in C/C++, all constants start with acronyms of two or more letters to indicate where and how they can be used. Like WM_CHAR is a constant where “WM” means “Windows Message” so that it can be used with SendMessage, GetMessage, PostMessage and TranslateMessage functions; similarly, GWL_STYLE is a constant representing the flag to get the basic styles for a window when you call GetWindowLong function. These prefixes make sense because for Windows, all constants are defined with #typedef directives and will be converted back to their original values once complied, constants are therefore weakly typed and there must be a way to distinguish these constants from the places and ways to use.

In C#, you can use enum to replace constant definitions. Enum is a primitive, strong type in .NET Framework to represent all enumeration elements such as WM_CHAR or GWL_STYLE. Enum is self-described, when refer to a value of a specified enum, the type name of that enum must be provided as well. Enum is strong typed to protect type safety, prevent conversions between different enum types directly so you will never get confused with the same value elements of different enum types. Because enum is self-described, the type name must exist when you refer an instance of an enum type, hence, prefix the enum values with type name is redundant, helpless and meaningless.

The following example shows the incorrect name convention for enum values, which contains prefix for its type name.

public enum TransactionMode
{
    TransactionModeCash,
    TransactionModeCreditCard,
    TransactionModeCheck,
    TransactionModeOther
}

The correct and recommended way to name the values show as following code.

public enum TransactionMode
{
    Cash,
    CreditCard,
    Check,
    Other
}

The type information of enum value is provided by developer tools, like Visual Studio IntelliSense.

Do not suppress a warning message from this rule in any case, try to avoid type name prefix when you are designing your enum types.

For more information, please see this MSDN link for CA1712.

Tags: , , ,

Comments (1) -

Yelinna
Yelinna Peru
2/6/2012 9:13:29 AM #

It is true, Enums are self described, this helped me a lot when, using some SDKs, the sample source code converted enums to integers.

Reply

Pingbacks and trackbacks (1)+

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Translate This Page

About Mark

Mark is a developer who works for building base class libraries and tools for developers.

Mark's Awards

Microsoft Community Contributor

Month List

Who visit this site

Recent Comments

Comment RSS