FlagsAttribute

  • Thread starter Thread starter Charles Jenkins
  • Start date Start date
C

Charles Jenkins

I want to know if FontStyle.Bold is set in a font's Style property.

MS's help file is full of lovely examples of how to OR flags together in order to set the property, but as usual, seems to be missing the other half of the equation: How do you test the darned flags?

These tests all give me a compiler errors in C#:

FontStyle fs = myFont.Style;
bool isBold;

isBold = (( fs & FontStyle.Bold ) == FontStyle.Bold );
isBold = ( bool )( fs & FontStyle.Bold );
isBold = (( fs & FontStyle.Bold ) != 0 );
isBold = (( fs & ( ulong ) FontStyle.Bold ) == ( ulong ) FontStyle.Bold );

Casting and logical ANDing of the FlagsAttribute values does not seem to work, despite examples I have found on the Internet, such as the page at http://weblogs.asp.net/wim/archive/2004/04/07/109095.aspx

There must be a correct way to test the flags. Can anyone here share it with me?
 
Your first example is correct; following works as expected (under 2.0, but
pretty sure it is fine in 1.1 as well):

static void Main(string[] args) {
Font font = new Font("Courier New", 10F);
Console.WriteLine(IsBold(font));
Console.WriteLine(IsBold(new Font(font, FontStyle.Bold |
FontStyle.Italic)));
}

static bool IsBold(Font font) {
FontStyle fs = font.Style;
bool isBold;
isBold = ((fs & FontStyle.Bold) == FontStyle.Bold);
return isBold;
}
 
Hmmm... You're absolutely right. I must have had a typo in my first attempt to get this to work. My code now looks like this, and compiles with no problem.

FontStyle fs = fromFont.Style;
bool isBold = (( fs & FontStyle.Bold ) == FontStyle.Bold );
bool isItalic = (( fs & FontStyle.Italic ) == FontStyle.Italic );
bool isUnderline = (( fs & FontStyle.Underline ) == FontStyle.Underline );
bool isStrikeout = (( fs & FontStyle.Strikeout ) == FontStyle.Strikeout );

Thanks for proving me wrong!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top