How to get int value from enum in C#
By FoxLearn 11/20/2024 7:33:34 AM 201
In C#, you can get the integer value of an enum by using a simple type cast.
How to get int value from enum in C#?
For example:
enum LicenseType { Free = 1, Trial = 2, Enterprise = 3 }
Just cast the enum, e.g.
LicenseType lic = LicenseType.Free; // Cast the enum value to int to get its integer representation int licValue = (int)lic;
The default underlying type for enums in C# is int
, so casting an enum to int
will work in most cases to retrieve its integer value.
Enums in C# can have different underlying types, such as `uint`, `long`, or `ulong`. If an enum uses one of these types, it should be cast to the specific underlying type of the enum, rather than `int`.
For example: Enum of long values in C#
public enum Country : long { None, Canada, UnitedStates = (long)int.MaxValue + 1; } // val will be equal to the *long* value int.MaxValue + 1 long val = (long)Country.UnitedStates;
You can assign long
values to enum members, but you cannot assign an enum value directly to an integral type without a cast.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Motiv MUI React Admin Dashboard Template
11/19/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024