This question already has answers here:
How do I check if more than one enum flag is set?
(5 answers)
Closed 2 years ago.
So I have a flags Enum
public Enum test
{
test1 = 1,
test2 = 2,
test3 = 4,
etc.
}
How can I test that one bit, and only one bit is set?
I've 100% done this before but my mind is not working this am!
To check that only a single bit is set in a number, the number must (by definition) be a power of two. As such, you can use the following to test:
int intVal = ((int)myEnumFlags);
bool singleBitIsSet = intVal != 0 && (intVal & (intVal-1)) == 0;
My favorite reference for this kind of thing:
http://aggregate.org/MAGIC
Related
This question already has answers here:
How to check if any flags of a flag combination are set?
(18 answers)
Closed 1 year ago.
I have a list of records that contains a flags enum value. I am trying to filter on one or more value based on the flags supplied. The description of the HasFlag method is as follows:
true if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, false.
I would expect given an enum:
[Flags]
public enum MyFlaggedEnum
{
Unknown = 0,
First = 1,
Second = 2,
Third = 4,
Fourth = 8,
Fifth = 16,
Sixth = 32
}
And a record set containing a mixture of these values, assume that there are at least one record for each of the flags:
When I filter on one value:
var myFilteredList = MyMainList.Where(w => w.flagValue.HasFlag(MyFlaggedEnum.Third));
// myFilteredList returns the correct subset of records
When I filter on multiple values:
var myFilteredListMultiple = MyMainList.Where(w => w.flagValue.HasFlag(MyFlaggedEnum.First | MyFlaggedEnum.Fourth));
// myFilteredList returns an empty set
Am I misusing the HasFlag method; if so, how?
I am looking for a way to quickly filter the results so they can be displayed to the user in a datagridview based on filters they supply at runtime and can be changed at any time. I could loop through them or union multiple sets based on the flag filters requested by the user, but, was looking for a clean way.
EDIT: Whoever closed this question referring to this: How to check if any flags of a flag combination are set? does not understand the question. No, I am not adding First | Second values to my enum!!
I suggest that you eschew HasFlag and just do it directly using bit operations:
var myFilteredListMultiple = MyMainList.Where(w => (w.FlagValue & (MyFlaggedEnum.First | MyFlaggedEnum.Fourth)) != 0);
Or if you have a set of bitflags passed in called, say, mask:
var myFilteredListMultiple = MyMainList.Where(w => (w.FlagValue & mask) != 0);
There's an ambiguity over whether HasFlag should mean "has all" vs "has any"; it is implemented as "has all". But it is also an inefficient (boxing) API, so honestly: it is probably better to simply not use it. For example, you could add your own extension methods:
public static bool HasAny(this MyFlaggedEnum value, MyFlaggedEnum any)
=> (value & any) != 0;
public static bool HasAll(this MyFlaggedEnum value, MyFlaggedEnum all)
=> (value & all) == all;
and use .HasAny(MyFlaggedEnum.First | MyFlaggedEnum.Fourth)
This question already has answers here:
How to compare enum and int values?
(7 answers)
What's the simplest way to compare an enum to a integer value return from a DB
(5 answers)
C# Enum - How to Compare Value
(5 answers)
Closed 5 years ago.
I have a simple enum with a few values
Enum Status{
Available,
Taken,
Sold//and many more
}
I want to check whether the status is somewhere in between the possible values(assuming the values are written in such an order that the lowest are the beginning of a process, and the last ones are the final steps of the process)
Something like
Status s1;//Some value
if(s1<5 && s1>3)
//The value is one of the enum values in those range
//(for example the job has already been accepted, but has still not been
//shipped)
Is it possible?
Thanks.
You can assign integer values to your enum and then check.
enum Status
{
Available = 1,
Taken = 2,
Sold = 3
//and many more
}
Status s1; // any value
if ((int)s1 <= 5 && (int)s1 >= 3)
This question already has answers here:
Finding an enum value by its Description Attribute [duplicate]
(3 answers)
Get enum from enum attribute
(7 answers)
Closed 8 years ago.
I have an enum width descriptions:
public enum PostTypes {
[Description("Business")]
Business = 1 << 0,
[Description("Design"]
Design = 1 << 1,
[Description("Marketing")]
Marketing = 1 << 2,
} // PostTypes
I would like to get an Enum based on Description, so:
1 - If I have String="Business" I would get PostTypes.Business.
2 - If I have String[] = new String[] { "Business", "Design" } I would have PostTypes.Business | PostTypes.Design.
UPDATE
I am using the following:
Enum.GetValues(typeof(PostTypes)).Cast<PostTypes>().Where(v => new String[] { "Business", "Design" }.Contains(v.GetDescription())).Aggregate((a, b) => a | b);
This is working even for Flag enums and string arrays.
Could someone, please, help me in creating an extension where I pass the enum type and use a func for setting the rule for search, either the Description attribute or any other.
How can I do this?
Thank You,
Miguel
This question already has answers here:
Total number of items defined in an enum
(10 answers)
Closed 8 years ago.
I need to know the number of enums that have been declared.
So far I am using the following which works but I wonder if there is a better way?
enum MyEnum
{
foo = 1,
bar = 2
}
int noOfEnums = Enum.GetNames(typeof(MyEnum)).Count();
noOfEnums will be 2;
You may try to use:
enum MyEnum
{
foo = 1,
bar = 2
}
var noOfEnums = Enum.GetNames(typeof(MyEnum)).Length;
The length property of this array equals the number of items defined in the enum
Also check Count Items in a C# Enum
This question already has answers here:
Non-unique enum values
(8 answers)
Closed 9 years ago.
In .NET can you have multiple enum values for the same integer?
eg.
public enum PersonGender
{
Unknown = 0,
Male = 1,
Female = 2,
Intersex = 3,
Indeterminate = 3,
NonStated = 9,
InadequatelyDescribed = 9
}
In C#, this is allowed, as per the C# Language Specication, version 4. Section 1.10 Enums doesn't explicitly mention the possibility but, later on in section 14 Enums, 14.3, we see:
Multiple enum members may share the same associated value. The example
enum Color {
Red,
Green,
Blue,
Max = Blue
}
shows an enum in which two enum members - Blue and Max - have the same associated value.
That works fine. There is absolutely nothing wrong with the code you posted. It compiles just fine and works in code, with the caveat that
PersonGender.NonStated == PersonGender.InadequatelyDescribed
I found this StackOverflow post related to this question. I think there is a very sensible discussion of how this works. Non-unique enum values
Now, I might also add that it is my opinion this would be an ambiguous (and therefore improper) use of an enum. It's important to write code that makes sense to someone else reading it, and in this case, I would be put off by this enum.
I would suggest that an enum would not be a right thing to use in your context instead you can use create a class and methods which can resolve your purpose. Something like this in your class:-
class A
{
static readonly ABCD= new Dictionary<int,string>
{
{ 1, "X" },
{ 2, "X" },
{ 3, "Y" }
{ 4, "Y" }
}
}