Was looking at another question, and was curious if there’s any difference at all (in operation or performance) between these two.
Given:
[Flags]
enum TransportModes
{
None = 0,
Bus = 1,
Train = 2,
Plane = 4
}
And a variable
var trip = TransportModes.Bus | TransportModes.Train;
-
if((trip & TransportModes.Bus) == TransportModes.Bus) ... -
if((trip & TransportModes.Bus)) != 0) ...
I know what they do bit wise, and I know that HasFlag replaces them. But Jon Skeet recommends one, and the MSDN docs recommend another.
Your second option will return true, if the values you gave your enum values are not powers of two. The first option doesn’t have this problem.
Example:
Explanation:
trip & TransportModes.Planeis 1 which is apparently!= 0, but not equal toTransportModes.Planewhich has a value of 5.However, if you don’t use powers of two for the values of a flag enum, you most likely have bigger issues. Think about what happens, if
Planewould have the value 3: You couldn’t tellBus | TrainandPlaneapart…