C# Enum
using System;
class Program
{
enum Importance
{
None,
Trivial,
Regular,
Important,
Critical
};
static void Main()
{
// 1.
Importance value = Importance.Critical;
// 2.
if (value == Importance.Trivial)
{
Console.WriteLine("Not true");
}
else if (value == Importance.Critical)
{
Console.WriteLine("True");
}
}
}
Output
True
Enums store special values. They make programs simpler. If you place constants directly where used, your C# program becomes complex. It becomes hard to change. Enums instead keep these magic constants in a distinct type.
Example
In this first example, we see an enum type that indicates the importance of something. An enum type internally contains an enumerator list. We use enums when we want readable code that uses constants. An enum type is a distinct value type that declares a set of named constants.
In this first example, we see an enum type that indicates the importance of something. An enum type internally contains an enumerator list. We use enums when we want readable code that uses constants. An enum type is a distinct value type that declares a set of named constants.
Hejlsberg et al., p. 585
Program that uses enums: C#
using System;
class Program
{
enum Importance
{
None,
Trivial,
Regular,
Important,
Critical
};
static void Main()
{
// 1.
Importance value = Importance.Critical;
// 2.
if (value == Importance.Trivial)
{
Console.WriteLine("Not true");
}
else if (value == Importance.Critical)
{
Console.WriteLine("True");
}
}
}
Output
True
We see a new variable with the identifier "value" is of the Importance type. It is initialized to Importance.Critical in part 1. At part 2, the variable is tested against other enum constants.
Tip:Enums can be used with IntelliSense in Visual Studio. Visual Studio will guess the value you are typing.
So:You can simply press tab and select the enum type you want. This is an advantage to using enum types.
No comments:
Post a Comment