Saturday, 15 August 2015

c# - Setting all values of an Flag enum except of one field -



c# - Setting all values of an Flag enum except of one field -

i've got next declaration

private uint mask; action<flagenum> setfield = new action<flagenum>(x => this.mask = (uint)x);

and next enum example:

[flags] public enum flagenum : uint { clear = 0x0, f1 = 0x1, f2 = f1 << 1, f3 = f2 << 1, f4 = f3 << 1, f5 = f4 << 1, f6 = f5 << 1 }

now want set flags except of 'clear' flag. i've tried this:

setfield(!flagenum.clear);

but next message

operator '!' cannot applied perand of type 'bitmask.flagenum'

setting flag with, example:

setfield(flagenum.f1)

works fine.

so question how can set fields of flagenum instead of 'clear' 1 approach? or not possible , have implement requirement.

in particular case, flagenum.clear set zero, means cannot "set". flags defined follows (shortened 8 bits):

clear = 00000000 f1 = 00000001 f2 = 00000010 f3 = 00000100 f4 = 00001000 f5 = 00010000 f6 = 00100000

so, if, say, f2, f3 , f5 combined, binary representation of value 00010110 - it's combination obtained bitwise or of 3 flags.

however, how clear supposed added there? clear zero, oring value not alter anything. instead, if none of other flags set, value automatically clear.

if not whant intended, start assigning 0x01 clear.

generally, can indeed remove single value flags variable, , thought negating flag's value right - in c#, bitwise not expressed tilde (~) rather exclamation mark used logical not.

so, inverted bit pattern of f2 11111101. remove f2 00010110, or not do, because result 11111111. instead, negated value has anded previous flags combination:

00010110 & 11111101 = 00010100 (f3, f5)

c# enums bit enum-flags

No comments:

Post a Comment