1

I would like to define structure which will contain eight flags. Is it possible to use byte type instead of 8 boolean fields in it? I would like to have something like this

struct mystruct
{
  byte first:1;
  byte second:1;
  ...
}

I want binary representation to give me flags value.

And what if I have some values which should take more than 1 bit, e. g. 2 or 4

szaman
  • 6,666
  • 13
  • 53
  • 81

2 Answers2

4

Yes, you can do it not with a struct but with an enum, like this:

[Flags]
public enum MyFlags
{
    First = 1,
    Second = 2,
    Third = 4,
    Fourth = 8
}
Dutts
  • 5,781
  • 3
  • 39
  • 61
3

Hi undercover It will be converted to bytes look to this:

    [FlagsAttribute]
    public enum mystruct: byte
    {
        first= 1,
        second =2
    }

Shall I also post for you the IL code?

more info : What does the [Flags] Enum Attribute mean in C#?

By the way Flags is simply shorthand for FlagsAttribute.

d51
  • 316
  • 1
  • 6
  • 23
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70