In C#, the Enum class is used to work with enumeration types, which are user-defined value types that consist of a set of named constants. Enumerations provide a way to define a collection of related named constants, which makes the code more readable and maintainable.
Declaration and Initialization
Look at the following code for declaration of enum datatype variable; the code declares an enum type named DaysOfWeek. The members of this enum are Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday.
public enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Once this enum is declared, you can create instances of it by assigning any of the defined members, like so:DaysOfWeek today = DaysOfWeek.Monday;
}
We define an enum type representing the days of the week and create an instance of that enum by assigning one of its enum values to a variable.
In C#, enum members cannot be complex data types. Enums can only have simple integral types as their underlying type, typically int, byte, sbyte, short, ushort, long, or ulong. Each member of an enum is essentially just a named constant, and they are represented as integral values. You can assign specific integral values to the members.
public enum ErrorCodes
{
NotFound = 404,
ServerError = 500,
Unauthorized = 401
}
Properties and Methods
The Enum class itself doesn't have many methods or properties, but it provides some important features for working with enumeration types. Here are the key properties and methods of the Enum class:
Properties:
1. GetNames: Returns an array of strings containing the names of the constants in the enumeration.
string[] enumNames = Enum.GetNames(typeof(MyEnum));
2. GetValues: Returns an array of the values of the constants in the enumeration.
MyEnum[] enumValues = (MyEnum[])Enum.GetValues(typeof(MyEnum));
3. IsDefined: Checks if a specified value exists within the enumeration.
bool isDefined = Enum.IsDefined(typeof(MyEnum), someValue);
Methods:
1. GetName: Returns the name of the constant associated with a specified value.
string enumName = Enum.GetName(typeof(MyEnum), someValue);
2. 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));
3. 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");
4. 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 should be 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, 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.
Here are the key differences:
1. Syntax and Usage:
- enum: This keyword is used to define an enumeration type. For example:
enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
- Enum: This is a 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, or to parse strings into enumeration values. { Just as class is a keyword and System is a class in .NET Framework, enum is a keyword to declare enum type and Enum is a class in .NET Framework.}
2. Enum Base Class:
- All enums implicitly inherit from the System.Enum class, which provides methods and properties to work with enumerations.
3. Capabilities:
- With enum, you define a custom enumeration with specific values. It is a value type and supports a set of named constants.
- 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.
No comments:
Post a Comment