c# - Compare month of year enum with datetime month -


i have enum:

public enum monthsoftheyear {     january = 1,     february = 2,     march = 4,     april = 8,     may = 16,     june = 32,     july = 64,     august = 128,     september = 256,     october = 512,     november = 1024,     december = 2048,     allmonths = 4095, }   

and datime.now.month.

for example if value of month 5 equals "may", how can compare month enum? example not work: if (!monthsofyear.any(x=>x.code.equals((monthsoftheyear)(1 << (currentdatetime.month - 1)))

this bit of strange way represent month, not difficult want.

the operator need left bit shift operator, <<. if imagine number string of bits,

0000 0000 1111 0000  (240 in binary) 

then bit shift operators shift them number of places left or right; shifting left 1

0000 0001 1110 0000  (480 in binary) 

in case, january bit 1 shifted left 0 times, february bit 1 shifted left 1 time, , on:

int may = 5; monthsoftheyear result = (monthsoftheyear)(1 << (may - 1)); 

make sense?

update:

what wrong code?

!monthsofyear.any(x=>x.code.equals((monthsoftheyear)(1 << (currentdatetime.month - 1))))) 

where monthsofyear 1 + 2 + 4 + 8 ?

you have number 1 + 2 + 4 + 8 15. not equal 1, 2, 4 or 8. don't want equality in first place.

to test whether flag set, use & operator.

let's make easier understand abstracting away helper method:

// bit "flag" set in bit field "flags"? static bool isflagset(int flags, int flag) {     return (flags & (1 << flag)) != 0; } 

make sure understand how works. if have flags

0000 0011 

and ask if flag 1 set shifts bit 1 left 1 place:

0000 0010 

and says "give me 1 if both corresponding bits set, 0 otherwise." that's

0000 0010 

that not zero, flag must have been set.

now can say:

bool result = isflagset((int)monthsofyear, currentdatetime.month - 1); 

this gives true if flag set, false otherwise.

make sense?


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -