Welcome Forums General PowerShell Q&A $null on the left or right side.

Viewing 3 reply threads
  • Author
    • #168694
      Topics: 9
      Replies: 8
      Points: 102
      Rank: Participant

      I have noticed to warning in PowerShell Tools for Visual Studio, when I write something like this:

      if($MyVar -eq $null)

      that $null should be on left side only. And I decided to do small experiment:

      if (@() -eq $null) { 'true' }else { 'false' }
      if (@() -ne $null) { 'true' }else { 'false' }
      if ($null -eq @()) { 'true' }else { 'false' }
      if ($null -ne @()) { 'true' }else { 'false' }
      If $null on the right side – the first two expressions return ‘false’ both. But, when null on the left side (last two expressions) – I’ve got ‘false’ and ‘true’.
      May somebody to explain in details this behavior ?
    • #168709
      Topics: 42
      Replies: 174
      Points: 629
      Helping Hand
      Rank: Major Contributor

      I get the same result from both, that  I’d expect….but I also have read that $Null should be on left….$null -eq $MyVar

      $MyVar = $null
      $something = "me"
      if ($MyVar -eq $null) { 'true' }else { 'false' }
      if ($MyVar -ne $null) { 'true' }else { 'false' }
      if ($something -eq $null) { 'true' }else { 'false' }
      if ($something -ne $null) { 'true' }else { 'false' }
      if ($null -eq $MyVar) { 'true' }else { 'false' }
      if ($null -ne $MyVar) { 'true' }else { 'false' }
      if ($null -eq $something) { 'true' }else { 'false' }
      if ($null -ne $something) { 'true' }else { 'false' }


    • #168730
      Topics: 9
      Replies: 431
      Points: 738
      Helping Hand
      Rank: Major Contributor
      5 -eq $null   # False
      @() -eq $null # $null
      $null -eq @() # False
      $null -eq 5   # False

      does it make sense now!?

      In other words, when $null on the left side the -eq or -ne operators will cause the expression to evaluate to True or False, whereas when $null is on the right side the expression will evaluate to $null or True or False. When the expression evaluates to $null, the ‘else’ branch of the ‘if’ statement is invoked.

    • #168853
      Senior Moderator
      Topics: 8
      Replies: 1164
      Points: 4,076
      Helping Hand
      Rank: Community Hero
Viewing 3 reply threads
  • The topic ‘$null on the left or right side.’ is closed to new replies.