Revisited: Enum values as bit flags - using FlagsAttribute

In one of my earlier posts about enum bit flags, using the FlagsAttribute, I incorrectly stated that the actual enum values did not have to be specified. Due to the comments on the post, I ran another test, this time a more conclusive one! See the C# code for this test below.

using
System;

public
class Test
{
[Flags]
public enum DodgyCarOptions
{
 NoExtras,
 AirCo,
 
TintedWindows,
 
Leather,
 
SunRoof
}

[Flags]
public enum CarOptions
{
 
NoExtras=0,
 
AirCo=1,
 
TintedWindows=2,
 
Leather=4,
 
SunRoof=8
}

public static void Main(string[] args)
{
 
DodgyCarOptions myoptions = DodgyCarOptions.AirCo | DodgyCarOptions.TintedWindows;
// 01 | 10
 
Console.WriteLine("Test DodgyOptions:\t"+((myoptions==DodgyCarOptions.Leather)?"Airco + Tinted Windows = Leather! Oops!":"Well...not that you'll ever see this..")); // 01 | 10 == 11 !!!

 
CarOptions myoptions2 = CarOptions.AirCo | CarOptions.TintedWindows; // 01 | 10
 
Console.WriteLine("Test Options:\t\t"+((myoptions2==CarOptions.Leather)?"Airco + Tinted Windows = Leather! Oops!":"Of course these values aren't equal.")); // 01 | 10 == 11 != 100;
}
}

Apologies for the mistake - and happy coding!

1 Comment

Comments have been disabled for this content.