Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

4.8 Enum Design

Enums are a special kind of value type. There are two kinds of enums: simple enums and flag enums.

Simple enums represent small, closed sets of choices. A common example of the simple enum is a set of colors. For example,

public enum Color {
  Red,
  Green,
  Blue,
   
}

Flag enums are designed to support bitwise operations on the enum values. A common example of the flags enum is a list of options. For example,

[Flags]
public enum AttributeTargets {
  Assembly  = 0x0001,
  Module   = 0x0002,
  Cass    = 0x0004,
  Struct   = 0x0008,
   
} 

Historically, many APIs (e.g., Win32 APIs) represented sets of values using integer constants. Enums make such sets more strongly typed, and thus improve compile-time error checking, usability, and readability. For example, use of enums allows development tools to know the possible choices for a property or a parameter.

  • The underlying type needs to be different than Int32 for easier interoperability with unmanaged code expecting different size enums.
  • A smaller underlying type would result in substantial savings in space. If you expect for enum to be used mainly as an argument for flow of control, the size makes little difference. The size savings might be significant if:
  • You expect the enum to be used as a field in a very frequently instantiated structure or class.
  • You expect users to create large arrays or collections of the enum instances.
  • You expect a large number of instances of the enum to be serialized.

For in-memory usage, be aware that managed objects are always DWORD aligned so you effectively need multiple enums or other small structures in an instance to pack a smaller enum with to make a difference, as the total instance size is always going to be rounded up to a DWORD.

4.8.1 Designing Flag Enums

4.8.2 Adding Values to Enums

It is very common to discover that you need to add values to an enum after you have already shipped it. There is a potential application compatibility problem when the newly added value is returned from an existing API, because poorly written applications might not handle the new value correctly. Documentation, samples, and FxCop rules encourage application developers to write robust code that can help applications deal with unexpected values. Therefore, it is generally acceptable to add values to enums, but as with most guidelines there might be exceptions to the rule based on the specifics of the framework.

  • + Share This
  • 🔖 Save To Your Account