user20126134
user20126134

Reputation: 1

Is there another equal way to write the code shown below? Option Strict does not allow this late binding

{With CurrentFont
   NewFontStyle = -((Not .Underline) * FontStyle.Underline)
   NewFontStyle += -(.Bold * FontStyle.Bold)
   NewFontStyle += -(.Italic * FontStyle.Italic)
End With}

I just do not understand how this code work. If someone could just explain the use of minus and asterisk signs I can probably figure the rest out.

Upvotes: 0

Views: 49

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

It appears to be using mathematical operations where what's actually desired are logical and bitwise operations. FontStyle is an Enum with the Flags attribute applied, indicating that multiple values can be combined. What that code appears to be doing is creating a FontSyle value with the same Bold and Italic values and the opposite Underline value of CurrentFont. That can be done far more succinctly using proper code:

NewFontStyle = CurrentFont.Style Xor FontSyle.Underline

If you want to make absolutely sure that Strikethrough is not set then you can do this:

NewFontStyle = CurrentFont.Style Xor FontSyle.Underline And Not FontStyle.Strikethrough

When performing bitwise operations, Or sets a bit, And Not resets a bit and Xor toggles a bit, so Or effectively adds a style, And Not removes a style and Xor toggles a style.

Depending on how this code is used, you may be able to improve more of the code by doing it properly. This code will effective toogle the Underline style of CurrentFont while leaving other styles as they are:

CurrentFont = New Font(CurrentFont, CurrentFont.Style Xor FontStyle.Underline)

Upvotes: 2

Related Questions