Hi before going to direct problem let me show my code :
//Definition of enum
public enum LogType
{
Warning = -2,
Error = -1,
Info = 0,
EruCtorDtor = 1,
Notifications = 2,
CommunicationWithAOT = 4,
ExecutedOrder = 8,
ERUInfo = 16,
DebugLog = 32,
}
//Use of enum
CurrentLogFlagSettings = nLogFlag;
LogFlagMap = new SortedDictionary<LogType, int>();
ulong mask = 1;
while(mask <= nLogFlag)
{
if ((nLogFlag & mask) == mask)
{
LogType type = (LogType)mask; //Step 1
string val = type.ToString(); //Step 2
//Processing the value
LogFlagMap.Add(type, tempVal)
LogMsg(val + " added", type);
}
mask <<= 1;
}
What I want is : Process step2 only after step1 has produced valid value. I mean value should be between range defined in enum definition. Otherwise I dont want to process it.
for e.g.
case 1 - Lets say mask value is 32,
its defined in enum. So type is
getting value DebugLog and so it
type.ToString() (i.e. "DebugLog"),
this is a valid case.
case 2- Lets
say mask value is 128 and its not
defined in enum, in this case I dont
want to process anything on 128
value. But what is happening its
geting value 128 in type and
type.ToString() is converting it
into 128. I dont want this, I want
to make sure whether 128 belongs to
enum values or not.
I want to prevent 2nd case to be executed. Is there any solution for my problem?
Please let me know if more details are needed.
You could use Enum.IsDefined, like so:
int value = 128;
Console.WriteLine(Enum.IsDefined(typeof(LogType), value)); // will print out False
Firstly, let me seriously apologise, Ive had like no sleep, so if I missed the point a little. Please, just ignore me.
You can enumerate your LogType with Enum.GetValues(typeof(LogType))), so you could step through and check a value against it. I had some code, but, I couldnt promise it compiled.
Bool isValid(int i)
{
foreach (LogType l in Enum.GetValues(typeof(LogType)))
{
if ((int)l == i) return true;
}
return false;
}
You can also use Enum.GetValues(typeof(LogType)) to get all the possible values for your enum and do what you want through that.
i.e.
var values = Enum.GetValues(typeof (LogType));
foreach (LogType type in values)
{
if (((int)type & nLogMask) == (int)type)
{
//value is valid, process the value
}
}
One addition to your code could be the addition of the [Flags] attribute to you enum, this then makes it clear that the enum values are for bitwise operations
e.g.
[Flags]
public enum LogType
{
Warning = -2,
Error = -1,
Info = 0,
EruCtorDtor = 1,
Notifications = 2,
CommunicationWithAOT = 4,
ExecutedOrder = 8,
ERUInfo = 16,
DebugLog = 32,
}
although to do this, you would need to change the values such that the Warning and Error take the top 2 bits of the enum value (assuming this is still necessary).
The c# Enum class also has the method GetName(). This might provide a nice and easy manner to retrieve the name of the value set
e.g.
Enum.GetName( typeof(LogType), 4 ); // result = CommunicationWithAOT
I have a library called Unconstrained Melody which allows you to express all of this in a type-safe generic way and avoids boxing too. Personally I prefer that over using Enum.IsDefined, but obviously that doesn't involve learning an extra library.
It's probably not worth using Unconstrained Melody if this is the only thing you need to do with your enum, but if you've got other similar operations, you may wish to consider it.
Related
I have a property LegalCaseStatus. My intention is to make the property to accept a predefined range of approved values. The range must be visible and unchanged throughtout my program. Here's an example of the list:
Plaintiff
Defendant
Third Party
Debitor
Creditor
Petitioner
So, the best way I could think of is to declare a static class, and fill it with corresponding constants:
public static class Participants
{
public const byte
Piaintiff = 0,
Defendant = 1,
ThirdParty = 2,
Debitor= 3,
Creditor = 4,
Petitioner = 5;
}
so after using a namespace I could just do:
public byte LegalCaseStasus = Plaintiff;
the only problem is, since it's just a byte member it'll accept anything that is byte:
LegalCaseStatus = 99; // ok
LegalCaseStatus = SomeOtherByteConstant; // ok
How do I protect the member LegalCaseStatus? Is my solution generally correct?
You can use enums - An enum is a special "class" that represents a group of constants (unchangeable/read-only variables). Sounds like the thing you describe in your question:
public enum Participants
{
Piaintiff = 0,
Defendant = 1,
ThirdParty = 2,
Debitor = 3,
Creditor = 4,
Petitioner = 5
}
After the enum definition you can use it exactly the way you want to:
Participants LegalCaseStasus = Participants.ThirdParty;
LegalCaseStasus = 99; // ERROR
byte underlying_value = (byte)LegalCaseStasus; // value == 2
Note: The underlying value of an enum is int! When you cast to byte you need to make sure there are no predefined values that exceed the byte limit.
Thanks for taking the time to try help me.
I've ran into a rather weird issue. I'm trying to loop through all the Enum values to check if my object contains the Enum flag. But for some reason, that I do not quite understand, in the foreach it says it always has the flag. But in the separate if statements it does work exactly how I wanted. But I do not want to repeat code 6 times, so I would like to have the foreach statement working.
Does anybody know what is happening? Maybe some background information why it's happening?
Sorry for my English, it's not my native language.
Thanks in advance!
Code is changed from the original, but it's essentially the same.
Code below.
[Flags]
public enum SampleEnum
{
Enum1 = 0,
Enum2 = 1,
Enum3 = 2,
Enum4 = 4,
Enum5 = 8,
Enum6 = 16,
};
SampleEnum sample = SampleEnum.Enum1 | SampleEnum.Enum2;
// This doesn't work
foreach (SampleEnum enum in Enum.GetValues(typeof(SampleEnum)))
{
// This is statement says it allways has the flags. Even tho it doesn't have the flag.
if(sample.HasFlag(enum))
{
// This is always true.
}
}
// This works
if (sample.HasFlag(SampleEnum.Enum2))
{
// true
}
// This works
if (sample.HasFlag(SampleEnum.Enum3))
{
// false
}
// This works
if (sample.HasFlag(SampleEnum.Enum4))
{
// false
}
}
I seem to recall that having an element with value 0 means that everything contains that when using the HasFlag with [Flags] directive. Try this code:
Enum.GetValues(typeof(MainSettings.ConnectedPrinters)).Cast<MainSettings.ConnectedPrinters>().Where(v => (int)v > 0).ToList())
This will iterate the list without the 0 valued flag.
You should never create Flags enum with a 0 value as it'll do bitwise comparison of the element with 0.
AnyEnumItem & 0 always equals 0.
Edit : Except for an "All item"
From MSDN about HasFlag:
If the underlying value of flag is zero, the method returns true.
You should check for zero before using HasFlag.
Here is the declaration of the RotateFlipType enumeration from .NET 4:
public enum RotateFlipType
{
Rotate180FlipXY = 0,
RotateNoneFlipNone = 0,
Rotate270FlipXY = 1,
Rotate90FlipNone = 1,
Rotate180FlipNone = 2,
RotateNoneFlipXY = 2,
Rotate270FlipNone = 3,
Rotate90FlipXY = 3,
Rotate180FlipY = 4,
RotateNoneFlipX = 4,
Rotate90FlipX = 5,
Rotate270FlipY = 5,
RotateNoneFlipY = 6,
Rotate180FlipX = 6,
Rotate90FlipY = 7,
Rotate270FlipX = 7,
}
I understand how the values are paired together for operations that would otherwise have the same result. The above enumeration becomes unfriendly when comparing debugger values against RotateFlipType.ToString values. Also not good for data binding scenarios. For example:
var value = RotateFlipType.RotateNoneFlipNone; // Debugger shows correct string for [value] which is [RotateNoneFlipNone].
var text = value.ToString(); // Output of [text] is [Rotate180FlipXY]. Presumably because it is declared first in the list.
Does this have anything to do with ordering of operations? Could they have not used [Flags] or split the enumeration into two (separating Rotation and Flipping)?
I realize the horse is long gone, no need to close the barn door, but...
These constants were chosen in this pattern to make image reflections easier.
To flip horizontally, one can use this simple operation:
rotation_value ^= 4;
Vertical flip:
rotation_value ^= 6;
Flip both at the same time (180 degree rotation):
rotation_value ^= 2;
Enums override the ToString method to use Enum.GetName in order to find the name of the given value. And for GetName, MSDN has the following remark:
If multiple enumeration members have the same underlying value, the
GetName method guarantees that it will return the name of one of those
enumeration members. However, it does not guarantee that it will
always return the name of the same enumeration member. As a result,
when multiple enumeration members have the same value, your
application code should never depend on the method returning a
particular member's name.
So, if multiple members have the same value, there is no guarantee that ToString will give you the original name.
In C, enums, internally equates to an integer. Therefore we can treat data types of enum as integer also.
How to achieve the same with C#?
Firstly, there could be two values that you're referring to:
Underlying Value
If you are asking about the underlying value, which could be any of these types: byte, sbyte, short, ushort, int, uint, long or ulong
Then you can simply cast it to it's underlying type. Assuming it's an int, you can do it like this:
int eValue = (int)enumValue;
However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order! (Credit to #JohnStock for the poke to clarify).
This example assigns each a new value, and show the value returned:
public enum MyEnum
{
MyValue1 = 34,
MyValue2 = 27
}
(int)MyEnum.MyValue2 == 27; // True
Index Value
The above is generally the most commonly required value, and is what your question detail suggests you need, however each value also has an index value (which you refer to in the title). If you require this then please see other answers below for details.
Another way to convert an Enum-Type to an int:
enum E
{
A = 1, /* index 0 */
B = 2, /* index 1 */
C = 4, /* index 2 */
D = 4 /* index 3, duplicate use of 4 */
}
void Main()
{
E e = E.C;
int index = Array.IndexOf(Enum.GetValues(e.GetType()), e);
// index is 2
E f = (E)(Enum.GetValues(e.GetType())).GetValue(index);
// f is E.C
}
More complex but independent from the INT values assigned to the enum values.
By default the underlying type of each element in the enum is integer.
enum Values
{
A,
B,
C
}
You can also specify custom value for each item:
enum Values
{
A = 10,
B = 11,
C = 12
}
int x = (int)Values.A; // x will be 10;
Note: By default, the first enumerator has the value 0.
You can directly cast it:
enum MyMonthEnum { January = 1, February, March, April, May, June, July, August, September, October, November, December };
public static string GetMyMonthName(int MonthIndex)
{
MyMonthEnum MonthName = (MyMonthEnum)MonthIndex;
return MonthName.ToString();
}
For Example:
string MySelectedMonthName=GetMyMonthName(8);
//then MySelectedMonthName value will be August.
Use simple casting:
int value = (int) enum.item;
Refer to enum (C# Reference)
Use a cast:
public enum MyEnum : int {
A = 0,
B = 1,
AB = 2,
}
int val = (int)MyEnum.A;
using System;
public class EnumTest
{
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
static void Main()
{
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
One reason that the designers c# might have chosen to NOT have enums auto convert was to prevent accidentally mixing different enum types...
e.g. this is bad code followed by a good version
enum ParkingLevel { GroundLevel, FirstFloor};
enum ParkingFacing { North, East, South, West }
void Test()
{
var parking = ParkingFacing.North; // NOT A LEVEL
// WHOOPS at least warning in editor/compile on calls
WhichLevel(parking);
// BAD wrong type of index, no warning
var info = ParkinglevelArray[ (int)parking ];
}
// however you can write this, looks complicated
// but avoids using casts every time AND stops miss-use
void Test()
{
ParkingLevelManager levels = new ParkingLevelManager();
// assign info to each level
var parking = ParkingFacing.North;
// Next line wrong mixing type
// but great you get warning in editor or at compile time
var info=levels[parking];
// and.... no cast needed for correct use
var pl = ParkingLevel.GroundLevel;
var infoCorrect=levels[pl];
}
class ParkingLevelInfo { /*...*/ }
class ParkingLevelManager
{
List<ParkingLevelInfo> m_list;
public ParkingLevelInfo this[ParkingLevel x]
{ get{ return m_list[(int)x]; } }}
In answering this question I define 'value' as the value of the enum item, and index as is positional location in the Enum definition (which is sorted by value). The OP's question asks for 'index' and various answer have interpreted this as either 'index' or 'value' (by my definitions). Sometimes the index is equal to numerical value.
No answer has specifically addressed the case of finding the index (not value) where the Enum is an Enum flag.
Enum Flag
{
none = 0 // not a flag, thus index =-1
A = 1 << 0, // index should be 0
B = 1 << 1, // index should be 1
C = 1 << 2, // index should be 2
D = 1 << 3, // index should be 3,
AandB = A | B // index is composite, thus index = -1 indicating undefined
All = -1 //index is composite, thus index = -1 indicating undefined
}
In the case of Flag Enums, the index is simply given by
var index = (int)(Math.Log2((int)flag)); //Shows the maths, but is inefficient
However, the above solution is
(a) Inefficient as pointed out by #phuclv (Math.Log2() is floating point and costly) and
(b) Does not address the Flag.none case, nor any composite flags - flags that are composed of other flags (eg the 'AandB' flag as in my example).
DotNetCore
If using dot net core we can address both a) and b) above as follows:
int setbits = BitOperations.PopCount((uint)flag); //get number of set bits
if (setbits != 1) //Finds ECalFlags.none, and all composite flags
return -1; //undefined index
int index = BitOperations.TrailingZeroCount((uint)flag); //Efficient bit operation
Not DotNetCore
The BitOperations only work in dot net core. See #phuclv answer here for some efficient suggestions https://stackoverflow.com/a/63582586/6630192
#user1027167 answer will not work if composite flags are used, as per my comment on his answer
Thankyou to #phuclv for suggestions on improving efficiency
This is a valid enum
public enum myEnum
{
a= 1,
b= 2,
c= 3,
d= 4,
e= 5,
f= 6,
g= 7,
h= 0xff
};
But this is not
public enum myEnum
{
1a = 1,
2a = 2,
3a = 3,
};
Is there a way I can use an number in a enum? I already have code that would populate dropdowns from enums so it would be quite handy
No identifier at all in C# may begin with a number (for lexical/parsing reasons). Consider adding a [Description] attribute to your enum values:
public enum myEnum
{
[Description("1A")]
OneA = 1,
[Description("2A")]
TwoA = 2,
[Description("3A")]
ThreeA = 3,
};
Then you can get the description from an enum value like this:
((DescriptionAttribute)Attribute.GetCustomAttribute(
typeof(myEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
.Single(x => (myEnum)x.GetValue(null) == enumValue),
typeof(DescriptionAttribute))).Description
Based on XSA's comment below, I wanted to expand on how one could make this more readable. Most simply, you could just create a static (extension) method:
public static string GetDescription(this Enum value)
{
return ((DescriptionAttribute)Attribute.GetCustomAttribute(
value.GetType().GetFields(BindingFlags.Public | BindingFlags.Static)
.Single(x => x.GetValue(null).Equals(value)),
typeof(DescriptionAttribute)))?.Description ?? value.ToString();
}
It's up to you whether you want to make it an extension method, and in the implementation above, I've made it fallback to the enum's normal name if no [DescriptionAttribute] has been provided.
Now you can get the description for an enum value via:
myEnum.OneA.GetDescription()
No, there isn't. C# does not allow identifiers to start with a digit.
Application usability note: In your application you should not display code identifiers to the end-user anyway. Think of translating individual enumeration items into user-friendly displayable texts. Sooner or later you'll have to extend the enum with an item whose identifier won't be in a form displayable to the user.
UPDATE: Note that the way for attaching displayable texts to enumeration items is being discusses, for example, here.
An identifier in C# (and most languages) cannot start with a digit.
If you can modify the code that populates a dropdown with the enumeration names, you could maybe have a hack that strips off a leading underscore when populating the dropdown and define your enum like so:
public enum myEnum
{
_1a = 1,
_2a = 2,
_3a = 3
};
Or if you don't like the underscores you could come up with your own 'prefix-to-be-stripped' scheme (maybe pass the prefix to the constructor or method that will populate the dropdown from the enum).
Short and crisp 4 line code.
We simply use enums as named integer for items in code,
so any simplest way is good to go.
public enum myEnum
{
_1 = 1,
_2,
_3,
};
Also for decimal values,
public enum myEnum
{
_1_5 = 1,
_2_5,
_3_5,
};
So while using this in code,
int i = cmb1.SelectedIndex(0); // not readable
int i = cmb1.SelectedIndex( (int) myEnum._1_5); // readable
No way. A valid identifier (ie a valid enumeration member) cannot start with a digit.
Enumerations are no different than variables in terms of naming rules. Therefore, you can't start the name with a number. From this post, here are the main rules for variable naming.
The name can contain letters, digits, and the underscore character
(_).
The first character of the name must be a letter. The underscore is
also a legal first character, but its
use is not recommended at the
beginning of a name. An underscore is
often used with special commands, and
it's sometimes hard to read.
Case matters (that is, upper- and lowercase letters). C# is
case-sensitive; thus, the names count
and Count refer to two different
variables.
C# keywords can't be used as variable names. Recall that a keyword
is a word that is part of the C#
language. (A complete list of the C#
keywords can be found in Appendix B,
"C# Keywords.")
Identifiers can't start with numbers. However, they can contain numbers.
Here is what i came up with as an alternative, where I needed Enums to use in a "for" Loop and a string representation equivalent to use in a Linq query.
Create enums namespace to be used in "for" Loop.
public enum TrayLevelCodes
{
None,
_5DGS,
_5DG,
_3DGS,
_3DG,
_AADC,
_ADC,
_MAAD,
_MADC
};
Create strings based on enum created to be used for Linq query
public string _5DGS = "\"5DGS\"",
_5DG = "\"5DG\"",
_3DGS = "\"3DGS\"",
_3DG = "\"3DG\"",
_AADC = "\"AADC\"",
_ADC = "\"ADC\"",
_MAAD = "\"MAAD\"",
_MADC = "\"MADC\"";
Create function that will take an enum value as argument and return corresponding string for Linq query.
public string GetCntnrLvlDscptn(TrayLevelCodes enumCode)
{
string sCode = "";
switch (enumCode)
{
case TrayLevelCodes._5DGS:
sCode = "\"5DGS\"";
break;
case TrayLevelCodes._5DG:
sCode = "\"5DG\"";
break;
case TrayLevelCodes._3DGS:
sCode = "\"3DGS\"";
break;
case TrayLevelCodes._3DG:
sCode = "\"3DG\"";
break;
case TrayLevelCodes._AADC:
sCode = "\"AADC\"";
break;
case TrayLevelCodes._ADC:
sCode = "\"AAC\"";
break;
case TrayLevelCodes._MAAD:
sCode = "\"MAAD\"";
break;
case TrayLevelCodes._MADC:
sCode = "\"MADC\"";
break;
default:
sCode = "";
break;
}
return sCode;
}
Here is how i am using what i created above.
for (var trayLevelCode = TrayLevelCodes._5DGS; trayLevelCode <= TrayLevelCodes._MADC; trayLevelCode++)
{
var TrayLvLst = (from i in pair1.Value.AutoMap
where (i.TrayLevelCode == HTMLINFO.GetCntnrLvlDscptn(trayLevelCode))
orderby i.TrayZip, i.GroupZip
group i by i.TrayZip into subTrayLvl
select subTrayLvl).ToList();
foreach (DropShipRecord tray in TrayLvLst)
{
}
}