Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

Enums

               attributes? access-modifier?
new?
enum enum-name [ : integer-type ]?
{ [attributes? enum-member-name 
[ = value ]? ]* }

Enums specify a group of named numeric constants:

public enum Direction {North, East, West, South}

Unlike in C, enum members must be used with the enum type name. This resolves naming conflicts and makes code clearer:

Direction walls = Direction.East;

By default, enums are assigned integer constants 0, 1, 2, etc. You may optionally specify an alternative numeric type to base your enum on, and explicitly specify values for each enum member:

[Flags]
public enum Direction : byte {
   North=1, East=2, West=4, South=8
}
Direction walls = Direction.North | Direction.West;
if((walls & Direction.North) != 0)
    System.Console.WriteLine("Can't go north!");

The [Flags] attribute is optional, and informs the runtime that the values in the enum can be bit-combined, and should be decoded accordingly in the debugger or when outputting text to the console. For example:

Console.WriteLine(walls.Format( )); // Displays "North|West"
Console.WriteLine(walls); // Calls walls.ToString, displays "5"

The System.Enum type also provides many useful static methods for enums that allow one to determine the underlying type of an enum, to check if a specific value is supported, to initialize an enum from a string constant, to retrieve a list of the valid values, and other common operations such as conversions. Here is an example of the usage:

using System; public enum Toggle : byte { Off=0, On=1 } class ...
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# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata