This question already has answers here:
How do I cast int to enum in C#?
(32 answers)
Closed 6 years ago.
If I have this code
//Spice Enums
enum SpiceLevels {None = 0 , Mild = 1, Moderate = 2, Ferocious = 3};
Which states the Enum Names + Their Number, how can I call an enum from a variable, say if a variable was 3, how do I get it to call and display Ferocious?
Just cast the integer to the enum:
SpiceLevels level = (SpiceLevels) 3;
and of course the other way around also works:
int number = (int) SpiceLevels.Ferocious;
See also MSDN:
Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int.
...
However, an explicit cast is necessary to convert from enum type to an integral type
enum SpiceLevels { None = 0, Mild = 1, Moderate = 2, Ferocious = 3 };
static void Main(string[] args)
{
int x = 3;
Console.WriteLine((SpiceLevels)x);
Console.ReadKey();
}
Enums inherit from Int32 by default so each item is assigned a numeric value, starting from zero (unless you specify the values yourself, as you have done).
Therefore, getting the enum is just a case of casting the int value to your enum...
int myValue = 3;
SpiceLevels level = (SpiceLevels)myValue;
WriteLine(level); // writes "Ferocious"
Related
I have an enum:
public enum EnumProductConfig
{
Color,
Fold,
Edge,
Hem,
Lift,
Tapes,
Control,
Clips,
Pull,
Val
}
The order of above values in enum is not alphabatical which is totally ok with me.
Now, I have a list with one of the property of type EnumProductConfig. I want to sort my list based on that property (which is of Enum type) in the order of appearance in the Enum. I do not want to sort it alphabetically. The order must stay as mentioned in my Enum. Hence all rows with value Color must come first. Followed by Fold etc.
Please advise.
myData.OrderBy(d => (int)d.ProductConfig).ToList();
Should do it. Import System.Linq
Enums are really just ints anyway, going from zero and increasing by 1. You can also give each value a specific int value if you want to.
Also, you should not prefix your enum type with the word enum as it is against the Microsoft naming guidelines.
In c#, an enum is a group of numeric value constants.
If not specified, the enum's underlying type is int:
Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int
And every enum member gets a value from 0 to n, where n is the number of members -1:
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
Since you didn't specify neither the underlying type nor the values, your enum is equivalent to:
public enum EnumProductConfig : int
{
Color = 0,
Fold = 1,
Edge = 2,
Hem = 3,
Lift = 4,
Tapes = 5,
Control = 6,
Clips = 7,
Pull = 8,
Val = 9
}
This means you can simply order by your EnumProductConfig property:
var list = new List<MyClass>()
var sorted = list.OrderBy(c => c.ProductConfig);
You can see a live demo on rextester.
For example, I have declared the following enum in C#.
C# code:
public enum LobMaster :int
{
RetailBroking = 1,
HNI = 2,
TechnologyInfrastructure = 3,
}
cshtml code:
#int code = 2
#if (LobMaster.RetailBroking == code)
{
}
If I try to compare int enum with integer value it gives me following error message.
operator '==' cannot be applied to types 'LobMaster' and 'int'
While my enum
LobMaster
is already an int type.
But when I cast the enum to int and then compare with int value it works fine.
So my question is why I need to cast enum to int as enum is already an int.
The main purpose of Enums is to remove "magic numbers", so you should ask yourself - why do you want to use those magic numbers?
Much better comparison would be:
Session["Lob_code"] is LobMaster && LobMaster.MassAffluent == (LobMaster)Session["Lob_code"]
This way you are avoiding those magic numbers and your code just provides all the context.
#if ((int) LobMaster.MassAffluent == Convert.ToInt32(Session["Lob_code"])) { }
you should be able to cast the left hand value and then do the conoarison
This question already has answers here:
Byte enum comparison in C#
(3 answers)
Closed 8 years ago.
I have set up a enum like this:
public enum ServerCommands:byte {
New = 0,
Join = 1,
}
And I want to use it like this:
byte command = buffer[0];
if (command == ServerCommands.Join) // Error: Operator == cannot be operands of type 'byte' and 'ServerCommands'.
Why is this not possible to do and how can I make it work? They are both of type byte.
You still need to cast from byte to ServerCommands! This is not done automatically. Assinging numbers to enum values is just for clarity when casting enum to int or other permitted numeric types.
Assigning numeric values to enum values does not change their type to the numeric type! You can cast any enum value to an int, as all enums (if not declared otherwise) can be cast to int, the first enum value having int value 0.
public enum MyEnum
{
First,
Second
}
is equal to
public enum MyEnum : int
{
First = 0,
Second
}
The feature of numbering enum values is required if the number is not linear, as in:
public enum ErrorCodes: int
{
Success = 0,
FileNotFound = 1,
MissingRights = 5,
WhatTheHeck = 18
}
You better state conversions explicitly:
if (command == (byte) ServerCommands.Join)
or even better:
if ((ServerCommands) command == ServerCommands.Join) //always convert to the more restrictive type.
This is a precaution to prevent one from comparing values without knowing that the objects are from a different type.
Equality means that both objects have the same type. This is not the case. ServerCommands extend from byte. Thus a byte is not per se a valid ServerCommands object...
Furthermore the : byte is more used as an explicit encoding. Having the same binary encoding does not imply two objects are the same. For instance 14.25f and 0x41640000 are binary the same...
You probably need to cast your enum:
if (command == (byte)ServerCommands.Join)
Why does this declaration,
public enum ECountry : long
{
None,
Canada,
UnitedStates
}
require a cast for any of its values?
long ID = ECountry.Canada;
// Error Cannot implicitly convert type 'ECountry' to 'long'.
// An explicit conversion exists (are you missing a cast?)
And is there a way to get a long value directly from the enum, besides casting?
This would not work either, for example:
public enum ECountry : long
{
None = 0L,
Canada = 1L,
UnitedStates=2L
}
The issue is not that the underlying type is still int. It's long, and you can assign long values to the members. However, you can never just assign an enum value to an integral type without a cast. This should work:
public enum ECountry : long
{
None,
Canada,
UnitedStates = (long)int.MaxValue + 1;
}
// val will be equal to the *long* value int.MaxValue + 1
long val = (long)ECountry.UnitedStates;
The default underlying type of enum is int. An enum can be any integral type except char.
If you want it to be long, you can do something like this:
// Using long enumerators
using System;
public class EnumTest
{
enum Range :long {Max = 2147483648L, Min = 255L};
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}
The cast is what is important here. And as #dlev says, the purpose of using long in an enum is to support a large number of flags (more than 32 since 2^32 is 4294967296 and a long can hold more than 2^32).
You must cast an enum to get a value from it or it will remain an enum type.
From MSDN:
In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the enumeration is long, the enumeration members must still be explicitly converted to type long using a cast.
// keyword_enum2.cs
// Using long enumerators
using System;
public class EnumTest
{
enum Range :long {Max = 2147483648L, Min = 255L};
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);
Console.WriteLine("Min = {0}", y);
}
}
Output
Max = 2147483648 Min = 255
AFAIK, you have got to cast.
The MSDN article says:
"However, an explicit cast is needed to convert from enum type to an integral type" (either int or long)
You can check it out:
Enumeration types (C# reference)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Cast int to Enum in C#
I fetch a int value from the database and want to cast the value to an enum variable. In 99.9% of the cases, the int will match one of the values in the enum declaration
public enum eOrderType {
Submitted = 1,
Ordered = 2,
InReview = 3,
Sold = 4,
...
}
eOrderType orderType = (eOrderType) FetchIntFromDb();
In the edge case, the value will not match (whether it's corruption of data or someone manually going in and messing with the data).
I could use a switch statement and catch the default and fix the situation, but it feels wrong. There has to be a more elegant solution.
Any ideas?
You can use the IsDefined method to check if a value is among the defined values:
bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
You can do
int value = FetchIntFromDb();
bool ok = System.Enum.GetValues(typeof(eOrderType)).Cast<int>().Contains(value);
or rather I would cache the GetValues() results in a static variable and use it over and over gain.