Christo S. Christov
Christo S. Christov

Reputation: 2309

Which one of these approaches to casting is the most effective?

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

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

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

Related Questions