Casting an integer to an enum in C# requires explicit casting. Here's how you can do it with an example using a simple enum:
Let's assume you have the following enum:
csharp
enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
To cast an integer to the DaysOfWeek enum, you need to ensure that the integer value corresponds to one of the enum values. Here's how you can do it:
csharp
int intValue = 2; // Assuming you want to cast 2 to DaysOfWeek enum
DaysOfWeek day = (DaysOfWeek)intValue;
Console.WriteLine(day); // Output: Tuesday
In this example, we're explicitly casting the integer 2 to the DaysOfWeek enum. The value 2 corresponds to Tuesday in the enum, so the cast is successful, and day will hold the value DaysOfWeek.Tuesday.
Keep in mind that you should make sure the integer value you're casting is within the valid range of the enum. If the integer value does not correspond to any enum value, you'll get an InvalidCastException at runtime.
Let's assume you have the following enum:
csharp
enum DaysOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
To cast an integer to the DaysOfWeek enum, you need to ensure that the integer value corresponds to one of the enum values. Here's how you can do it:
csharp
int intValue = 2; // Assuming you want to cast 2 to DaysOfWeek enum
DaysOfWeek day = (DaysOfWeek)intValue;
Console.WriteLine(day); // Output: Tuesday
In this example, we're explicitly casting the integer 2 to the DaysOfWeek enum. The value 2 corresponds to Tuesday in the enum, so the cast is successful, and day will hold the value DaysOfWeek.Tuesday.
Keep in mind that you should make sure the integer value you're casting is within the valid range of the enum. If the integer value does not correspond to any enum value, you'll get an InvalidCastException at runtime.
Comments
Post a Comment