5

Today I see this code:

ViewBag.country = from p in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures)
                              select new SelectListItem
                              {
                                  Text = p.EnglishName,
                                  Value = p.DisplayName
                              };

And I can not understand. "~" - This is a mistake? As far as I remember, "~" is placed before the destructors. But this is enum. And this code compiled!

CMaker
  • 664
  • 1
  • 6
  • 17
  • http://stackoverflow.com/q/93744/284240 – Tim Schmelter Apr 12 '13 at 09:50
  • 1
    `~` isn't the only symbol with multiple unrelated meanings. There's `*`: pointers and multiplication have little to do with each other. –  Apr 12 '13 at 09:54
  • 1
    @CuongLe no it isn't; at the individual bit level, 0 &~ 1 => 0, where- as 0 ^ 1 => 1. Or to take a concrete example: 3 &~ 5 => 2, 3 ^ 5 => 6. In this example 3 and 5 are binary `0011` and `0101`, deliberately chosen to create a truth-table. If `&~` was "equal with" `^`, the result would be identical. – Marc Gravell Apr 12 '13 at 10:03
  • @MarcGravell: you are right – cuongle Apr 12 '13 at 10:09

1 Answers1

6

It's bitwise negation operator.

~ Operator (C# Reference)

The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, long, and ulong.

And because operations on integral types are generally allowed on enumeration you can use ~ with enums backed with types listed above.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 4
    Useful for enumerations that are marked with `FlagsAttribute` (as are the other bitwise operators). – Oded Apr 12 '13 at 09:50