Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

4.5. Using Enumerated Members in a Bitmask

Problem

An enumeration of values is needed to act as bit flags that can be ORed together to create a combination of values (flags) in the enumeration.

Solution

Mark the enumeration with the Flags attribute:

[Flags]
enum Language
{
    CSharp = 0x0001, VBNET = 0x0002, VB6 = 0x0004, Cpp = 0x0008
}

Combining elements of this enumeration is a simple matter of using the bitwise OR operator (|). For example:

Language lang = Language.CSharp | Language.VBNET;

Discussion

Adding the Flags attribute to an enumeration marks this enumeration as individual bit flags that can potentially be ORed together. Using an enumeration of flags is no different than using a regular enumeration type. It should be noted that failing to mark an enumeration with the Flags would not generate an exception or a compile-time error even if the enumeration were used as bit flags.

The addition of the Flags attribute provides you with three benefits. First, if the Flags attribute is placed on an enumeration, the ToString and ToString("G") methods return a string consisting of the name of the constant(s) separated by commas. Otherwise, these two methods return the numeric representation of the enumeration value. Note that the ToString("F") method returns a string consisting of the name of the constant(s) separated by commas, regardless of whether this enumeration is marked with the Flags attribute. For an indication of why this works in this manner, see the "F" formatting type in ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata