Search code examples
c#.netoperatorstype-conversioncomparison-operators

Do "x as X != null" and "x is X" always return the same result?


Is there any situation where these two if statements will produce different results?

if(x as X != null)
{
  // Do something
}

if(x is X)
{
  // Do something
}

Edit: To clarify: I know what is the difference between the operators (in general) and what they mean. The question is if there is any situation where these two would produce different results.


Solution

  • Is there any situation where these two if statements will produce different results?

    First, note that there are more restrictions on the use of as than of is, so x is X may compile in cases where (x as X) != null may not. For example, as requires that the specified type be a reference type or a nullable type; is works with non-nullable value types as well.

    Assume now that both x is X and (x as X) != null are valid expressions. According to §7.10.11 of the C# 4.0 specification, "the operation E as T produces the same result as E is T ? (T)(E) : (T)null". If we plug that latter expression into (x as X) != null, we get

        (x as X) != null
    ==  ((x is X) ? (X)x : null) != null  // by the definition of "as"
    ==  (x is X) ? ((X)x != null) : (null != null)  // distribute
    ==  (x is X) ? true : false  // because (x is X) implies (x != null)
    ==  x is X
    

    This proves that x is X and (x as X) != null are equivalent if both are valid expressions.