Attribute, bitwise operations and enumerations : the FontStyle example

Posted by on Comments (1)

Recently, one of my clients was borred about a customisation of a .NET 2.0 RichTextBox control.

He was using a ToolStrip to change the style of text selections :

The problem he met was about the toggling between the different styles.

If you take a look at the FontStyle enumeration, you'll see that it "has a FlagsAttribute attribute that allows a bitwise combination of its member values" (cfr MSDN).

Knowing that, the values correlated to the different FontStyle are :

  • Regular : 0 (binary representation : 0000)
  • Bold : 1 (binary representation : 0001)
  • Italic : 2 (binary representation : 0010)
  • Underline : 4 (binary representation : 0100)
  • Strikeout : 8 (binary representation : 1000)

The fact that enumeration constants are defined in power of 2 is of required by the FlagsAttribute to avoid overlaps of different combinations.

Imagine that the selected text in the RichTextBox is bold and underlined. You'll get a FontStyle constant of 5 (binary representation : 0101).

If you ask to remove the bold style, you'll then just have to apply a XOR operator :

0101 XOR 0001 = 0100

If you then want to toggle again :

0100 XOR 0001 = 0101

The code in C# will thus be something like (rtb is the reference to the RichTextBox):

Font f = new Font(this.rtb.Font.FontFamily, this.rtb.Font.Size, this.rtb.SelectionFont.Style ^ FontStyle.Bold);
this.rtb.SelectionFont = f;

Easy, isn't it? :)

This will of course apply to all the enumeration types that have the FlagsAttribute.

Posted in: .NET 2.0   Tags: