Possible Duplicate:
What does the bitwise or | operator do?
new Font(textBox1.Font, FontStyle.Bold | FontStyle.Italic);
What does the method signature that accepts this constructor call look like?
I never knew I could use the '|' operator in a method call. I would like to know more about it.
What is the English word for the '|' operator? (I don't even know how to google it as I do not know a word to describe it)
When it is used in a method, how do I explain it to another developer?
Would you recommend that I include this operator in my bag of tricks?
Does the operator have any special caveats?
The signature of the accepting method just looks like:
public Font(Font prototype, FontStyle newStyle)
{
...
}
The |
operator (bitwise-or) in this context means that the font should be both bold and italic. It works like this because FontStyle
is an enum
decorated with a FlagsAttribute
. The FontStyle
definition is:
[Flags]
public enum FontStyle
{
Bold = 1,
Italic = 2,
Regular = 0,
Strikeout = 8,
Underline = 4
}
So when you say FontStyle.Bold | FontStyle.Italic
, it is bitwise-OR:
FontStyle.Bold = 1 = 00000001
FontStyle.Italic = 2 = 00000010
========
FontStyle.Bold | FontStyle.Italic = 3 = 00000011
Later, you can test the style
parameter to see which bits are set using another bitwise operators (&
). For example, if you want to see if the resulting style above is Bold, you can do:
FontStyle myStyle = FontStyle.Bold | FontStyle.Italic;
bool isBold = (myStyle & FontStyle.Bold) == FontStyle.Bold;
For example, the Bold
property on the Font
class checks if FontStyle.Bold
was part of the style you gave it using almost the same code as above:
public bool Bold
{
get
{
return ((this.Style & FontStyle.Bold) != FontStyle.Regular);
}
}
Note that starting in .NET Framework 4 you could use Enum.HasFlag()
to test the presence of a flag. For example, the above property definition could be reduced to (using a little syntactic sugar from C# 6):
public bool Bold => this.Style.HasFlag(FontStyle.Bold);
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