I'm always surprised that even after using C# for all this time now, I still manage to find things I didn't know about...
I've tried searching the internet for this, but using the "~" in a search isn't working for me so well and I didn't find anything on MSDN either (not to say it isn't there)
I saw this snippet of code recently, what does the tilde(~) mean?
/// <summary>
/// Enumerates the ways a customer may purchase goods.
/// </summary>
[Flags]
public enum PurchaseMethod
{
All = ~0,
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4
}
I was a little surprised to see it so I tried to compile it, and it worked... but I still don't know what it means/does. Any help??
Just a side note, when you use
you have the added benefit that
Cash | Check | CreditCard
would evaluate toAll
and not to another value (-1) that is not equal to all while containing all values. For example, if you use three check boxes in the UIand sum their values, and the user selects them all, you would see
All
in the resulting enum.Because of two complement in C#,
~0 == -1
, the number where all bits are 1 in the binary representation.For others who found this question illuminating, I have a quick
~
example to share. The following snippet from the implementation of a paint method, as detailed in this Mono documentation, uses~
to great effect:Without the
~
operator, the code would probably look something like this:... because the enumeration looks like this:
Notice this enum's similarity to Sean Bright's answer?
I think the most important take away for me is that
~
is the same operator in an enum as it is in a normal line of code.I'd think that:
Would be a bit more clear.
Its better than the
solution, because if you add another method later, say:
you will be already done with the tilde-All, but have to change the all-line with the other. So its less error-prone later.
regards
It's a complement operator, Here is an article i often refer to for bitwise operators
http://www.blackwasp.co.uk/CSharpLogicalBitwiseOps.aspx
Also msdn uses it in their enums article which demonstrates it use better
http://msdn.microsoft.com/en-us/library/cc138362.aspx