Setting enum flags from integer value - c#

CompBitsList companyBit;
public CompBitsList CompanyBit { get => companyBit; set => companyBit= value; }
[Flags]
public enum CompBitsList
{
None = 0
BitOption1 = 1,
BitOption2 = 2,
BitOption3 = 4,
BitOption4 = 8,
BitOption5 = 16,
BitOption6 = 32,
}
Lets say I have the integer value 22 that would contain the enum flags BitOption2, BitOption3 and BitOption5 (2+4+16). Is there a way to automate this so that I can pass the integer value and have the enum variable CompanyBit set automatically?
companyBit = CompBitsList.BitOption2 | CompBitsList.BitOption3 | CompBitsList.BitOption5
I'm not very familar with enums but I would prefer not to do the method above so any suggestions are appreciated. Thanks :)

You can just cast the int to an instance of CompBitsList.
CompBitsList companyBit = (CompBitsList)22;
companyBit.HasFlag(CompBitsList.BitOption2); // True
companyBit.HasFlag(CompBitsList.BitOption3); // True
companyBit.HasFlag(CompBitsList.BitOption5); // True
companyBit.HasFlag(CompBitsList.BitOption6); // False
You can also define a value on that enum that represents a combination of flags, if it makes sense and you'll be combining those flags a lot.
[Flags]
public enum CompBitsList
{
None = 0
BitOption1 = 1,
BitOption2 = 2,
BitOption3 = 4,
BitOption4 = 8,
BitOption5 = 16,
BitOption6 = 32,
BitOptions2And3And5 = BitOption2 | BitOption3 | BitOption5 //or just 22
}

Related

How to use flags to check if something from the collection matches the flag

I'm trying to use flags to filter collection and retrive certain objects.
Perhaps the example will show the issue.
I defined a class and an enum.
public class ExampleFlagsDto
{
public int FlagId { get; set; }
public string Name { get; set; }
}
[Flags]
public enum FlagsTypes
{
None = 0,
Small = 1 << 0 ,
Medium = 1 << 1 ,
Normal = 1 << 2,
Large = 1 << 3,
LargeAndNormal = Normal | Large,
All = Normal | Medium | Small | Large,
}
Then I constructed a list as an example and tried to retrive 2 objects from the list.
var examples = new List<ExampleFlagsDto>()
{
new ExampleFlagsDto
{
FlagId = (int)FlagsTypes.Normal,
Name = "First"
},
new ExampleFlagsDto
{
FlagId = (int)FlagsTypes.Medium,
Name = "Second"
},
new ExampleFlagsDto
{
FlagId = (int)FlagsTypes.Large,
Name = "Third"
},
new ExampleFlagsDto
{
FlagId = (int)FlagsTypes.Small,
Name = "Forth"
},
};
var selected = examples.Where(C => C.FlagId == (int)FlagsTypes.LargeAndNormal).ToList();
foreach (var flag in selected)
{
Console.WriteLine(flag.Name);
}
Of course, it doesn't work. I know that when it comes to bits, (int)FlagTypes.LargeAndNormal would result in a sum of bits of Large and Normal. I have no idea how it has to look like bitwise, though.
I'm looking for a way to change the
examples.Where(C => C.FlagId == (int)FlagsTypes.LargeAndNormal).ToList();
to a solution that would result in selected having 2 objects from examples.
You could try this solution:
var selectedAll = examples.Where(C => (C.FlagId & (int)FlagsTypes.All) == (int)C.FlagId).ToList();

Enum.HasFlag is not working as expected [duplicate]

This question already has answers here:
HasFlag always returns True
(5 answers)
Closed 4 years ago.
I have a Enum with Flags like this:
[Flags]
public enum ItemType
{
Shop,
Farm,
Weapon,
Process,
Sale
}
Then I have several objects in a list with some flags set and some flags not set. It looks like this:
public static List<ItemInfo> AllItems = new List<ItemInfo>
{
new ItemInfo{ID = 1, ItemType = ItemType.Shop, Name = "Wasserflasche", usable = true, Thirst = 50, Hunger = 0, Weight = 0.50m, SalesPrice = 2.50m, PurchasePrice = 5, ItemUseAnimation = new Animation("Trinken", "amb#world_human_drinking#coffee#female#idle_a", "idle_a", (AnimationFlags.OnlyAnimateUpperBody | AnimationFlags.AllowPlayerControl)) },
new ItemInfo{ID = 2, ItemType = ItemType.Sale, Name = "Sandwich", usable = true, Thirst = 0, Hunger = 50, Weight = 0.5m, PurchasePrice = 10, SalesPrice = 5, ItemUseAnimation = new Animation("Essen", "mp_player_inteat#pnq", "intro", 0) },
new ItemInfo{ID = 3, ItemType = (ItemType.Shop|ItemType.Process), Name = "Apfel", FarmType = FarmTypes.Apfel, usable = true, Thirst = 25, Hunger = 25, Weight = 0.5m, PurchasePrice = 5, SalesPrice = 2, ItemFarmAnimation = new Animation("Apfel", "amb#prop_human_movie_bulb#base","base", AnimationFlags.Loop)},
new ItemInfo{ID = 4, ItemType = ItemType.Process, Name = "Brötchen", usable = true, Thirst = -10, Hunger = 40, Weight = 0.5m, PurchasePrice = 7.50m, SalesPrice = 4}
}
Then I go trough the list with a loop and ask if the flag ItemType.Shop is set or not, like this:
List<ItemInfo> allShopItems = ItemInfo.AllItems.ToList();
foreach(ItemInfo i in allShopItems)
{
if (i.ItemType.HasFlag(ItemType.Shop))
{
API.consoleOutput(i.Name);
}
}
This is the output of my loop - it shows all items in the list, and the .HasFlag method always returns true in this case.
Wasserflasche
Sandwich
Apfel
Brötchen
Try to assign values to your enum
[Flags]
public enum ItemType
{
Shop = 1,
Farm = 2,
Weapon = 4,
Process = 8,
Sale = 16
}
Here are some Guidelines for FlagsAttribute and Enum (excerpt from Microsoft Docs)
Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.
Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
You should assign values to your enums. All the flags attribute does is change how the ToString method works. I would use a bitwise operator to make it less likely to make a mistake:
[Flags]
public enum ItemType
{
Shop = 1 << 0, // == 1
Farm = 1 << 1, // == 2
Weapon = 1 << 2, // == 4
Process = 1 << 3, // == 8
Sale = 1 << 4 // == 16
}

Loop through enum result property

I have a model with a enum property. When I call my service, the model is returned back, and my enum-property contains the following data: Test1 | Test2 | Test3.
I want to loop through the propery and assign the values to a list.
How can I do this with an enum propery?
var form = await _formService.GetById();
That code above generates a result with a enum property called Sections with th data that I provided above, but I don't know how to loop through It to get the values.
Here is my Enum:
[Flags]
public enum Sections
{
Test1= 0,
Test2= 1,
Test3= 2,
Test4= 4,
}
Is this what you are looking for?
[Flags]
public enum Sections
{
Test1 = 0,
Test2 = 1,
Test3 = 2,
Test4 = 4,
}
public static List<Sections> getSectionsFromFlags(Sections flags)
{
var returnVal = new List<Sections>();
foreach (Sections item in Enum.GetValues(typeof(Sections)))
{
if ((int)(flags & item) > 0)
returnVal.Add(item);
}
return returnVal;
}
If you have defined enum like this
[Flags]
public enum Sections
{
Test1 = 0,
Test2 = 1,
Test3 = 2,
Test4 = 4,
}
Then
var someValue = Sections.Test1 | Sections.Test3 | Sections.Test4;
var values = Enum.GetValues(typeof(Sections))
.OfType<Sections>().Where(x=>(x&someValue)==x)
.ToArray();
values now contains all three value Sections.Test1 | Sections.Test3 | Sections.Test4
Another solution (from comments)
var values = Enum.GetValues(typeof(Sections))
.OfType<Sections>()
.Where(x=>someValue.HasFlag(x))
.ToArray();
Last one Is most correct, I think.

where is the enum declared from user input c#

I have two enums and I want to determine from user input(string), in which array is the enum with the same name from user input
public enum LengthUnit
{
mm = -3,
cm = -2,
dm = -1,
m = 0,
km = 3
}
public enum NumericUnit
{
b = 2,
o = 8,
d = 10,
h = 16
}
string input = "cm";
Sounds like you want Enum.TryParse which will let you pass a string and the enum type as parameters and an out parameter as the result if the TryParse succeeds.

Represent a Number as a Binary in C#

I have four checkboxes and user can select any check box and I want to store checked checkboxes in a single value. Logic should be like
Item Value
Checkbox1 1
Checkbox2 2
Checkbox3 4
Checkbox4 8
If a user selects Checkbox1 and Checkbox2 then it should be stored 3 If select Checkbox1, Checkbox2 and Checkbox3 then it should be stored 7. It will store some of value. Now I want to derive selected checkboxes from stored value, that means if a value is 7 then Checkbox1, Checkbox2 and Checkbox3 are selected.
How can I achieve this? If any can help me on this.
To determine which checkboxes should be checked, use the bitwise AND operator:
Checkbox1.Checked = value & 1;
Checkbox2.Checked = value & 2;
Checkbox3.Checked = value & 4;
Checkbox4.Checked = value & 8;
use an enum with the Flags attribute:
[Flags]
public enum CheckBoxEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
Value4 = 8,
}
You can then check the results using bitwise operations:
var res = CheckBoxEnum.Value1 | CheckBoxEnum.Value2;
var res2 = CheckBoxEnum.Value1 & CheckBoxEnum.Value2;
UPD:
#Glorfindel answer is more elegant, but you should use Bitwise OR instead of AND
Checkbox1.Checked = value | 1;
Checkbox2.Checked = value | 2;
Checkbox3.Checked = value | 4;
Checkbox4.Checked = value | 8;
You are looking for FlagsAttribute, applied to Enum
[Flags]
public enum CheckboxesSelected
{
Checkbox1 = 1,
Checkbox2 = 2,
Checkbox3 = 4,
Checkbox4 = 8
}
Then:
if your checkboxes controls is selected, you can do something like this:
CheckboxesSelected result = CheckboxesSelected.Checkbox1 | CheckboxesSelected.Checkbox2; //result will be 3

Categories