Pregunta

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.

¿Fue útil?

Solución 2

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.

Otros consejos

There functionally is no difference between the 2 statements. In general the as version is used to avoid a double type test because you can do the following

var local = x as X;
if (local != null) { 
  // Sweet I have local! 
}

vs.

if (x is X) { 
  // This runs the type check yet again 
  var local = (X)x; 
}

If you aren't actually using the value after the type test then just use the is version

If x is a non-nullable type (or a generic type not constrained to be a nullable type) then the first option won't compile; the second is the only option.

Beyond that, they're the same.

In this case:

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

You are first attempting to cast x to type X before comparing to null (i.e. whether the cast succeeded or not).

In this other case:

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

You are simply asking whether x is of type X and no casting is done.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top