Pergunta

Possible Duplicate:
C# “as” cast vs classic cast

What is the difference between these two expressions?

  • (ListView)sender
  • sender as ListView

In General, I usually used the exp sender as ListView. But in SO i find that most times users use (ListView)sender.

So, I want to know which one is more efficient.

Or,

If it is the choice of the coder, which one to use[and both works the same way]??

Foi útil?

Solução

The difference is that (ListView)sender will throw an exception if sender isn't a ListView, but sender as ListView will not throw an exception and return null instead if the cast is invalid.

Outras dicas

The difference would be that if for some reason sender was not castable to a ListView, (ListView)sender would throw an exception, while sender as ListView will cause the result to be null.

var listview = (ListView)sender  // Throws an exception if sender is not listView

and

var listview = sender as ListView  // listview will be assigned to null if sender is not
                                   // a listview

as operator doesn't throw an exception when it fails but instead fills the Left-Hand-Side variable with null.

While (ListView)sender will throw exception if sender is not ListView.

Using (a)b will throw an exception if b is not assignable to a or cannot be converted, and can be used even when a is a non-nullable type (like int). Using b as a will never throw an exception (it returns null if b cannot be assigned to a), but will not convert (e.g. you can do (int?)12.3 but not 12.3 as int?) and will not work if a isn't nullable (e.g. you can do 12 as int? but not 12 as int).

sender as ListView is the same as:

sender is ListView ? (ListView)sender : null

There is practically no difference in efficiency. as is safe against invalid casts since it produces a null result instead of throwing an exception, so I always use as and then check for the null condition.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top