I have the following code, and am wondering if there's a way to write the bitwise operator in the last section (Copy Files Only) to include both setting it to the All value and then removing the other two on a single line.
private void cbInstallType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbInstallType.Text == "Full Install")
{
eventFlags = GBFEvents.All;
}
else if (cbInstallType.Text == "DB Only")
{
eventFlags = (GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
}
else if (cbInstallType.Text == "Copy Files Only")
{
eventFlags = GBFEvents.All;
eventFlags &= ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
}
}
GBFEvents is defined thusly:
public enum GBFEvents
{
NONE = 0,
InitGBFSQL = 1 << 0,
ServiceIISControlDown = 1 << 1,
SetWebConfigValues = 1 << 2,
ReadFilelists = 1 << 3,
CopyFiles = 1 << 4,
FixWebConfigValues = 1 << 5,
BuildAppPaths = 1 << 6,
PerformDatabaseUpdate = 1 << 7,
ServiceIISControlUp = 1 << 8,
All = ~(-1 << 9)
}
Changing it to a single line is a pretty simple case of just expanding what things do. So going step by step:
var eventFlags = GBFEvents.All;
eventFlags &= ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
If we expand the &= we get:
var eventFlags = GBFEvents.All;
eventFlags = eventFlags & ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
If we then inline the use of eventFlags in the second line we get:
var eventFlags = GBFEvents.All & ~(GBFEvents.InitGBFSQL | GBFEvents.PerformDatabaseUpdate);
I know you've already got an acceptable answer for your question, but I'd still prefer something like this in your enum:
public enum GBFEvents
{
NONE = 0,
InitGBFSQL = 1 << 0,
ServiceIISControlDown = 1 << 1,
SetWebConfigValues = 1 << 2,
ReadFilelists = 1 << 3,
CopyFiles = 1 << 4,
FixWebConfigValues = 1 << 5,
BuildAppPaths = 1 << 6,
PerformDatabaseUpdate = 1 << 7,
ServiceIISControlUp = 1 << 8,
/* Helpers */
AllDBEvents = InitGBFSQL | PerformDatabaseUpdate,
AllServiceEvents = ServiceIISControlDown | ServiceIISControlUp,
AllConfigEvents = SetWebConfigValues | FixWebConfigValues,
AllFileEvents = ReadFilelists | CopyFiles | BuildAppPaths,
All = AllDBEvents | AllServiceEvents | AllConfigEvents | AllFileEvents
}
(I may have mischaracterized BuildAppPaths, you may consider it more Config related, as an example)
And then your code here would be:
eventFlags = AllServiceEvents | AllConfigEvents | AllFileEvents;
(And the other path would just use AllDbEvents)
This, to me, makes it clearer on reading that "Copy Files Only" isn't just copying files whilst not having to have tonnes of options |ed together on that line. And these helper values in your enum may be reusable in other areas too.
The main idea is to make the "named groups" of events explicit in your enum rather than having to correctly combine them in other parts of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With