-1

I have often wondered which is the better way of checking the type of an object before carrying out an operation.

I could use the 'is' operator:

if(obj is MyClass){
    var tObj = obj as MyClass;
}

Or I could use the 'as' operator and test for null:

var tObj = obj as MyClass;

if(tObj != null){

}

Is one preferable to the other? Is one way quicker? Does it matter?

Michael Edwards
  • 6,308
  • 6
  • 44
  • 75

2 Answers2

0

Second way is preferable, because it is quicker.

In the second way you only call the operator as once and do a null check which is much more cheaper compared to as/is operators.

tafa
  • 7,146
  • 3
  • 36
  • 40
0

It depends how you are using it,

For example, if the visibility of panels depends on the type of an object, then is would be better since you may not need to use the object again.

But for the examples you have provided, as would be better since you have a working object to use.

Sayse
  • 42,633
  • 14
  • 77
  • 146