Reputation: 2309
I have been wondering about that for quite a while now.
if(something is MyType){
var item = something as MyType;
}
Or
var item = something as MyType;
if(item != null){
}
Upvotes: 1
Views: 44
Reputation: 186668
The 2nd version
var item = something as MyType;
if (item != null) {
...
}
is better: just one type conversion (as
) not two (is
and then as
).
The 1st version (a bit modified) can be used for struct
that are not nullable:
// you can't put "as" for struct, i.e "something as int"
if (something is int) {
int item = (int) something; // note changed type conversion
...
}
Upvotes: 2