Use single bool and bit flags for other bools.
-
Hi, I have 10 bool variables in a class. Instead of creating 10 bools, how to create a single bool and bit flags for remaining 9 bool variables inorder to efficiently use memory. Can I have a code snippet in C# for this.. Thanks in Advance.
If you want this to cover a flag uint from interop or something else where you don't want an enum, you can do something like
public struct Flags {
public uint Value;public bool this[int i] {
get { return 1 & (Value >> i); }
set { uint mask = 1 << i; Value = (Value & ~mask) | (value ? 1 : 0) << i; }
}
}... to provide indexed access to a set of flags.
-
Does it?
-
SledgeHammer01 wrote:
I wouldn't expose an enum from object though ... I would have 10 public properties
I have either one public property or use a parameter (for a method or the constructor as appropriate) to pass in an Options enumerated value, as with passing options to a Regex.
Bad idea (sometimes). Property grids (i.e. in designers) don't play nicely with flag enums. Also, flag enums don't play nicely with data binding if you are using WPF or even Winforms.
-
OP wrote:
I have 10 bool variables in a class. Instead of creating 10 bools, how to create a single bool and bit flags for remaining 9 bool variables inorder to efficiently use memory.
It does.
Bastard Programmer from Hell :suss:
Does not -- they may very wel be related.
-
If you want this to cover a flag uint from interop or something else where you don't want an enum, you can do something like
public struct Flags {
public uint Value;public bool this[int i] {
get { return 1 & (Value >> i); }
set { uint mask = 1 << i; Value = (Value & ~mask) | (value ? 1 : 0) << i; }
}
}... to provide indexed access to a set of flags.
But I think that can only test one bit at a time.
-
Bad idea (sometimes). Property grids (i.e. in designers) don't play nicely with flag enums. Also, flag enums don't play nicely with data binding if you are using WPF or even Winforms.
SledgeHammer01 wrote:
flag enums don't play nicely with ... Winforms.
I haven't had that problem.
-
Does not -- they may very wel be related.