Is there a VB.net equivalent for C#'s ! operator?

前端 未结 6 1737
旧巷少年郎
旧巷少年郎 2020-12-19 14:02

After two years of C#, I\'m now back to VB.net because of my current job. In C#, I can do a short hand testing for null or false value on a string variable like this:

<
相关标签:
6条回答
  • 2020-12-19 14:29

    Yes they are the same

    0 讨论(0)
  • 2020-12-19 14:33

    They work identically until you reference C or C++ code.

    For example doing NOT on the result of a Win32 API function, might lead to incorrect result, since true in C == 1, and a bitwise NOT on 1 does not equal false.

    As 1 is        00000000001
    Bitwise Not    11111111110
    While false is 00000000000
    

    However in VB it works just fine, as in VB true == -1

    As -1 is       11111111111
    Bitwise Not    00000000000
    
    0 讨论(0)
  • 2020-12-19 14:41

    c# : boolean example1 = false;

     boolean example2 = !example1;
    

    vb.net: dim example1 as boolean = False

        dim example2 as boolean = Not example1
    
    0 讨论(0)
  • 2020-12-19 14:45

    Seconded. They work identically. Both reverse the logical meaning of the expression following the !/not operator.

    0 讨论(0)
  • 2020-12-19 14:47

    Not is exactly like ! (in the context of Boolean. See RoadWarrior's remark for its semantics as one's complement in bit arithmetic). There's a special case in combination with the Is operator to test for reference equality:

    If Not x Is Nothing Then ' … '
    ' is the same as '
    If x IsNot Nothing Then ' … '
    

    is equivalent to C#'s

    if (x != null) // or, rather, to be precise:
    if (object.ReferenceEquals(x, null))
    

    Here, usage of IsNot is preferred. Unfortunately, it doesn't work for TypeOf tests.

    0 讨论(0)
  • 2020-12-19 14:50

    In the context you show, the VB Not keyword is indeed the equivalent of the C# ! operator. But note that the VB Not keyword is actually overloaded to represent two C# equivalents:

    • logical negation: !
    • bitwise complement: ~

    For example, the following two lines are equivalent:

    • C#: useThis &= ~doNotUse;
    • VB: useThis = useThis And (Not doNotUse)
    0 讨论(0)
提交回复
热议问题