juergen d
juergen d

Reputation: 204894

"Expression is always false" when casting with AS

I get the compiler warning

Expression is always false

on this code

void Test(Part part) {
   var wire = part as Wire;    
   if (wire == null) return;

   if (part == null) {  //here I get the warning
      ....
   }
}

But if the cast to Wire fails and results in null does not mean part is null too.

Is this a wrong warning or am I wrong?

Wire is a subclass of Part

Upvotes: 0

Views: 155

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502825

But if the cast to Wire fails and results in null does not mean part is null too.

No, but the reverse is true - if part is null, then wire will definitely be null, so you'll already have returned... hence the warning. (I'm assuming you don't change the value of part in the intervening code.)

Basically, you've got a stricter check earlier - it's a bit like this:

int value = ...;

if (value < 10)
{
    return;
}
...
if (value < 0)
{
    return;
}

If value is less than 0, then it's definitely less than 10, so we won't get past the first check.

Hopefully that's a simpler condition to understand - then apply that to the relationship between part and wire and when they can have null values.

Upvotes: 3

Related Questions