O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Related Constants with enum

The enum[10] keyword lets us define a type whose values can be one of a fixed set of possibilities. Example 3-21 declares an enum for our Direction property. You can add this to an existing source file, above or below the Plane class, for example. Alternatively, you could add a whole new source file to the project, although Visual Studio doesn’t offer a file template for enum types, so either you’d have to add a new class and then change the class keyword to enum, or you could use the Code File template to add a new, empty source file.

Example 3-21. Direction enum

enum DirectionOfApproach
{
    Approaching,
    Leaving
}

This is similar in some respects to a class declaration. We can optionally begin with a protection level but if, like Example 3-21, we omit that, we get internal protection by default. Then there’s the enum specifier itself, followed by the name of the type, which by convention we PascalCase. Inside the braces, we declare the members, again using PascalCasing. Notice that we use commas to separate the list of constants—this is where the syntax starts to part company with class. Unusually, the members are publicly accessible by default. That’s because an enum has no behavior, and so there are no implementation details—it’s just a list of named values, and those need to be public for the type to serve any useful purpose.

Note

Notice that we’ve chosen to call this DirectionOfApproach, and not the plural DirectionsOfApproach. By convention, we give

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required