I’m working with some old code, trying to improve it, and I came across the following, which I am having trouble understanding:
controlToUpdate.Font =
new System.Drawing.Font(someFont,
someFontSize,
controlToUpdate.Font.Style ^
(controlToUpdate.Font.Style & FontStyle.Bold));
Specifically, I am confused as to what the last parameter does. As I understand it, the following should do a bitwise comparison, and return the result:
controlToUpdate.Font.Style ^ (controlToUpdate.Font.Style & FontStyle.Bold)
..but what does that mean in this situation? What are the possible results, that may be passed as the third parameter to new Font(...), and how can I rewrite this more clearly, while keeping with the intent of the original programmer?
Sidenote: Is this a normal way to do things when working with Windows Forms? I’m a little new in that area – is the intent here obvious to coders more experienced in this field?
performs an “and” to return
FontStyle.Boldif the style (controlToUpdate.Font.Style) includes bold, and0if the style does not include bold: basically, it gets just the “bold” bit.performs an “xor”; if the bold bit was set, it removes it; if the bold bit was not set, then it does nothing (since “xor” with 0 is a no-op).
So basically, that complicated code just removes the “bold” bit (if it is set). A simpler implementation would have been:
How that works: here, the
~FontStyle.Boldinverts all the bits;FontStyle.Boldis1:so
~FontStyle.Boldis:we then “and” that with our current style, which means it keeps all of the old style except the bold-bit.