Enumeration is a custom data type which contains an sequence of names written inside the body of the enum separated by comma. For example,
public enum Direction
{
North,
East,
West,
South
}
{
North,
East,
West,
South
}
The names in the sequence have underlying integral values, if not explicitly assigned. If values are not assigned to names then the first name has value 0, second one has value 1, third has value 2 and so on. You can assign any arbitrary numeric integral values to the names. For example,
public enum Direction
{
North = 3,
East = 1,
West = 2,
South = 4
}
Syntax version1
accessModifier enum EnumName : EnumDataType
{
value1, value2, ...valueN
}
Syntax version2
accessModifier enum EnumName : EnumDataType
{
value1=number1, value2=number2, ... valueN=numberN
}
Declaration and Initialization
Look at the following code for declaration of enumeration type (in short, enum type).
public enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday=9,
Saturday
}Points to note:
- The code declares an enum type named Days.
- The named numeric constants of this enum are Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday.
- They are numeric constants because they have underlying numeric integral values.
- The underlying value of first constant Sunday is 0, Monday is 1 and so on.
- You can explicitly assign a numeric value to constant e.g. Friday=9. In this case, if next constant is not assigned value then underlying value will be 1 more than previous one. So, Saturday=10.
- The convention is to write each named constant in Pascal or upper case.
Named Numeric Constants
- Each named numeric constant has a underlying numeric integral value.
- The underlying value of first named numeric constant is 0 if not explicitly assigned a value.
- You can explicitly assign a numeric value to named numeric constant.
- More than one named numeric constant can have same value.
- The convention is to write each named constant in Pascal or upper case.
- The named numeric constants cannot be floating point type or complex data types. They can only have simple integral types as their underlying type, typically int, byte, sbyte, short, ushort, long, or ulong.
- Named numeric constant cannot be assigned method, even if method returns an integer value. The expression being assigned to the named numeric constant must be constant.
Example. You can assign a constant to enum named constant.
enum Colors { Red = 0, Green = 0, Blue = Test.ColorValue }
class Test
{
public const int ColorValue = 3;
}
Default value of Enumeration
The default named numeric constant of Enumeration is the first constant which value is 0. If two named numeric constants have 0 value then the first constant is the default one. If no named numeric constant has value 0 then you get 0.
enum Days { }
enum Directions { South = 0, North = 0, East, West }
enum Colors { Red = 0, Green = 0, Blue = 3 }
enum WeekDays
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Test
{
static void Main(string[] args)
{
Console.WriteLine(default(Days)); // 0
Console.WriteLine(default(Directions)); // 0
Console.WriteLine(default(WeekDays)); // Sunday
Console.WriteLine(default(Colors)); // Red
}
}
Enum Variable
You define a variable of enumeration type and assign it a value from the numeric constant given in the enumeration type. For example, you define a variable of Days enum type and assign it a value out of the numeric constants given in the Days :
Days today = Days.Monday;
Here,
- Days is an enumeration data type,
- today is enum variable/identifier and
- Days.Monday is the value assigned to the enum variable.
- Note that today can be assigned only named constant, which belong to Days.
- So, it provides saftely in assigning value to enumeration variable.
Example
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Test
{
static void Main(string[] args)
{
Days today = Days.Wednesday;
Console.WriteLine("Today is: " + Days.Wednesday);// Wednesday
Console.WriteLine("Today is: " + today); // Wednesday
today = (Days)2; // typecast 2 to Days enum type
Console.WriteLine("Today is: " + today); // Tuesday
today = (Days)11;// typecast 11 to Days enum type
// since 11 is not defined in the Days enum, it will be treated as an integer value
Console.WriteLine("Today is: " + today); // 11
int number = (int)Days.Friday; // typecast Days.Friday to int
Console.WriteLine("Value of Friday: " + number); // 5
}
}
Notes.
- Days.Wednesday returns just the numeric constant name- Wednesday.
- Number can be cast to enum type to get numeric constant name. But if the number is not assigned to any named constant in the enum, you get the number not the numeric constant name.
- The named numeric constant name can be typecast into integer and vice versa.
Syntax of Enumeration type
- Enumeration type has access modifier: public, private, protected, internal, file and
- Access modifier is optional in enum declaration.
- Access modifier is followed by enum keyword and then identifier for enumeration type is Pascal case e.g. Direction, WeekDays etc.
- In the body of enum type declaration, named constants are written in Pascal case separated by comma.
- Each named constant can be assigned a numeric integral value. By default, they are int type.
- To explicitly define the type of named constants, you can use type, int, byte, sbyte, short, ushort, long, or ulong. after the enum identifier, preceded by colon.
Example1. Constant names have implicit integer valuespublic enum Direction{ North, East, West, South}
Example2. Constant names have explicit integer valuesinternal enum Direction{ North = 3, East = 1, West = 2, South = 4}
Example3. Constant names have explicit byte valuesfile enum Direction : byte{ North = 3, East = 1, West = 2, South = 4}
Example4. Constant names have duplicate valuesprivate enum Status{ Pending = 1, Waiting = 1, Approved = 2}
Example5. Constant name may have value based on previous name valueprotected enum Width{ Narrow = 2, Medium, Large} // Here Medium = 3, Large = 4
public enum Direction
{
North,
East,
West,
South
}
{
North = 3,
East = 1,
West = 2,
South = 4
}
{
North = 3,
East = 1,
West = 2,
South = 4
}
Example4. Constant names have duplicate values
private enum Status
{
Pending = 1,
Waiting = 1,
Approved = 2
}
Example5. Constant name may have value based on previous name value
protected enum Width
{
Narrow = 2,
Medium,
Large
} // Here Medium = 3, Large = 4
Example of Use of Enumeration in switch case
enum Quality
{
Low,
Medium,
High
}
class Program
{
static void Main(string[] args)
{
Quality quality = Quality.Medium;
switch (quality)
{
case Quality.Low:
Console.WriteLine("Quality is Low");
break;
case Quality.Medium:
Console.WriteLine("Quality is Medium");
break;
case Quality.High:
Console.WriteLine("Quality is High");
break;
default:
Console.WriteLine("Unknown Quality");
break;
}
}
}
Enum Vs Enumeration types
The enum keyword is used to define custom enumeration types, which are value type. The System.Enum is a built-in abstract class, which is reference type. Every enum type implicitly derives from System.Enum.
What Enumeration types (enum) cannot do
- Enumeration types (enum) is allowed inside class/struct/interface.
- Multiple Enumeration types (enum) is allowed inside same class.
- Enumeration types (enum) is allowed as Type argument in closed generic type.
- You can use an enum as a method parameter type.
- You can use an enum as a method return type.
What Enumeration types (enum) cannot do
- Enumeration types do not allow inheritance in C#. But enums implicitly inherit from System.Enum.
- Enumeration types cannot inherit from another enum.
- Enumeration types cannot be inherited.
- Enumeration types cannot implement interfaces.
- Enumeration types cannot define methods directly because an enum is intended to represent a fixed set of named integral values, not behavior. But Extension methods let you write method-like behavior for enums.
- Enumeration types can specify floating-point number for its numeric constants.
- The enum values support only a limited set of operations because an enum represents named integral constants.
Example of Limited set of operations with enum values
enum Colors { Red = 1, Green = 2, Blue = Test.ColorValue }
class Test
{
public const int ColorValue = 4;
static void Main(string[] args)
{
Console.WriteLine(Colors.Red > Colors.Blue); // False
Console.WriteLine(Colors.Red >= Colors.Blue); //False
Console.WriteLine(Colors.Red <= Colors.Blue); //True
Console.WriteLine(Colors.Red < Colors.Blue); // True
Console.WriteLine(Colors.Red - Colors.Blue); // -3
Console.WriteLine(Colors.Red == Colors.Blue); //False
Console.WriteLine(Colors.Green); // Green
Console.WriteLine((int)Colors.Red); // 1
}
}
Relation of System.Enum with enum
- Enum is an abstract class.
- All enum types are custom types. They derive from built-in type - Enum class.
- Enumeration types are user-defined value types that consist of a set of named constants but Enum is a reference type.
- Enumerations provide a way to define a collection of related named constants, which makes the code more readable and maintainable. Enum class provides methods and properties to help all enumeration types e.g. get names of enum.
Enum class - Properties and Methods
The Enum class has methods or properties, which provide some important features for working with enumeration types. Here are the key properties and methods of the Enum class:
Properties
- GetNames: Returns an array of strings containing the names of the constants in the enumeration.
- string[] enumNames = Enum.GetNames(typeof(MyEnum));
- GetValues: Returns an array of the values of the constants in the enumeration.
- MyEnum[] enumValues = (MyEnum[])Enum.GetValues(typeof(MyEnum));
- IsDefined: Checks if a specified value exists within the enumeration.
- bool isDefined = Enum.IsDefined(typeof(MyEnum), someValue);
Methods
- GetName: Returns the name of the constant associated with a specified value.
- string enumName = Enum.GetName(typeof(MyEnum), someValue);
- GetUnderlyingType: Returns the underlying type of the enumeration, which is typically an integral type (e.g., int, byte, etc.) used to represent the values of the constants.
- Type underlyingType = Enum.GetUnderlyingType(typeof(MyEnum));
- Parse: Converts a string representation of the constant name to its corresponding enum value. It's similar to Enum.TryParse, which is a static method of the specific enum type.
- MyEnum parsedValue = (MyEnum)Enum.Parse(typeof(MyEnum), "EnumValueName");
- ToObject: Converts an integral value to an enum object of the specified enum type.
- MyEnum enumObject = (MyEnum)Enum.ToObject(typeof(MyEnum), intValue);
These properties and methods allow you to work with enumeration types, retrieve information about their constants, and perform operations like parsing and converting values. Note that many of these methods are static and are called on the Enum class itself, while some can be called on a specific enum type directly.
How can you find the integer value of an enum member in C#?
In C#, you can obtain the integer value associated with an enum member using explicit casting or using the Convert class. Here's how you can achieve this:
1. Using Explicit Casting:
You can explicitly cast the enum member to its underlying type (usually int) to obtain its integer value.
enum MyEnum
{
Value1 = 10,
Value2 = 20
}
// Get the integer value of an enum member using explicit casting
int intValue = (int)MyEnum.Value1;
Console.WriteLine("Integer value of MyEnum.Value1: " + intValue); // Output: 10
2. Using Convert.ToInt32():
The Convert.ToInt32 method can also be used to convert the enum member to its integer value.
enum MyEnum
{
Value1 = 10,
Value2 = 20
}
// Get the integer value of an enum member using Convert.ToInt32()
int intValue = Convert.ToInt32(MyEnum.Value1);
Console.WriteLine("Integer value of MyEnum.Value1: " + intValue); // Output: 10
Both methods will give you the integer value associated with the enum member.
How can you find enum for given integer value of the enum in C#?
In C#, you can find the enum associated with a given integer value by iterating over the enum values and comparing the integer value with each enum value. Here's a step-by-step approach to achieve this:
1. Define an enum in C#.
2. Iterate over the enum values and compare the integer value with each enum value to find the matching enum.
Here's a code example:
using System;
public enum MyEnum
{
Value1 = 10,
Value2 = 20,
Value3 = 30
}
class Program
{
static void Main(string[] args)
{
int intValueToFind = 20;
MyEnum foundEnum = FindEnumByIntValue(intValueToFind);
if (foundEnum != MyEnum.Value1)
{
Console.WriteLine("Enum found: " + foundEnum);
}
else
{
Console.WriteLine("No matching enum found for the given integer value.");
}
}
public static MyEnum FindEnumByIntValue(int intValue)
{
foreach (MyEnum enumValue in Enum.GetValues(typeof(MyEnum)))
{
if ((int)enumValue == intValue)
{
return enumValue;
}
}
// If no matching enum is found, return a default value (e.g., Value1).
return MyEnum.Value1;
}
}
In this example, we define an enum called MyEnum with integer values. The FindEnumByIntValue method iterates over the enum values and compares each enum value with the given integer value to find the matching enum.
Enum vs enum: Differences
In C#, "enum" (lowercase) is a keyword used to declare an enumeration type, which is a set of named integral constants. An enumeration, or enum, defines a list of related named constants, often representing a set of possible values that a variable can hold.
On the other hand, "Enum" (uppercase) is the base class for enumerations in C#. It is a class within the .NET Framework that provides functionalities to work with enumerations.
- Enum is an built-in abstract class in System namespace.
- All enmeration types are custom types. They derive from Enum class. So, the methods and properties of System.Enum class can be used by custom enumeration types.
- Enum is a class name but enum is a keyword to define custom enumeration types.
Here are the key differences:
1. Syntax and Usage:
enum: This keyword is used to define an enumeration type. For example:
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Enum: This is a built-in class provided by the .NET Framework, and you use it to work with enumeration types, for example,
- to retrieve the names or values of enumeration constants
- to parse strings into enumeration values.
2. Enum is Base Class for all enumerations: All enums implicitly inherit from the System.Enum class, which provides methods and properties to work with enumerations.
3. Capabilities:
- With enum keyword, you define a custom enumeration type with specific numeric values. Enumerations are value type.
- With Enum class, you can perform operations on enumeration types, such as converting enumeration values to and from strings, getting the names or values of enumeration constants, and more.
In summary, "enum" is the keyword used to define a custom enumeration, while "Enum" is the base class in the .NET Framework that provides functionality for working with enumerations.
Examples of Methods and Properties of Enum class
enum Quality
{
Low,
Medium,
High
}
class Program
{
static void Main(string[] args)
{
// q is Quality variable with value Medium
// q can be assigned only values defined in Quality enum (Low, Medium, High)
// so, q cannot be assigned any other value like 5 or "Medium"
Quality q = Quality.High;
Console.WriteLine(q);
// prints the underlying integer value of High, which is 2
Console.WriteLine((int)q);
// this is valid because enums are backed by integers, but q=1 is invalid
q = (Quality)1;
Console.WriteLine(q);
// returns true because q is assigned the value of Medium (1)
bool areEqual = Enum.Equals(q, Quality.Medium);
Console.WriteLine(areEqual);
Enum.GetName(typeof(Quality), 2); // returns "High"
Enum.GetNames(typeof(Quality)); // returns array of names ["Low", "Medium", "High"]
// prints all names of Quality enum
Enum.GetNames(typeof(Quality)).ToList().ForEach(Console.WriteLine);
Enum.GetValues(typeof(Quality)); // returns array of values [0, 1, 2]
// returns true and result is assigned Quality.Medium
Enum.TryParse<Quality>("Medium", out Quality result);
// returns false and result2 is assigned default value of Quality (Low)
Enum.TryParse<Quality>("5", out Quality result2);
// returns true and result3 is assigned Quality.High
Enum.TryParse<Quality>("High", out Quality result3);
}
}
No comments:
Post a Comment