What is the tilde (~) in the enum definition?

Hugoware picture Hugoware · Dec 22, 2008 · Viewed 27.7k times · Source

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??

Answer

Jimmy picture Jimmy · Dec 22, 2008

~ is the unary one's complement operator -- it flips the bits of its operand.

~0 = 0xFFFFFFFF = -1

in two's complement arithmetic, ~x == -x-1

the ~ operator can be found in pretty much any language that borrowed syntax from C, including Objective-C/C++/C#/Java/Javascript.