开发者

When to use 'as' and when to use 'is' in C# [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate: casting vs using the 'as' keyword in the CLR

As someone new to C# I was wondering if there is any important difference between this:

object o = S开发者_开发百科omeFunction();
if (o is MyClass)
{
    MyClass myObject = (MyClass) o;
    myObject.MyFunction();
}

and this:

object o = SomeFunction();
MyClass myObject = o as MyClass;
if (myObject != null)
    myObject.MyFunction();

When is one preferred over the other? In the code I work with, both seem to be used randomly.


You should use what gives the most readable code. So it really depends on what you are doing.

IMHO, the is keyword is evil. It invites you to break the Liskov substitution principle.


The second sample won't work for value types as as operator would return null if casting fails. In C#, 'is' operator return true if object's type matches with your provided type else returns false.


The is operator checks whether an object is compatible with a given type, and the result of the evaluation is a Boolean: true or false. The is operator will never throw an exception.

The as operator works just like casting except the as operator will never throw an exception. Instead, if the object can’t be cast, the result is null. Regular cast '(Type)' will throw an exception if failed. Note that casting null using 'as' produces null. Hence, a null result from an 'as'-cast doesn't always mean that an object isn't of a given type, it could be that the instance is null.


As per your code, if 'o' needs to be used for some operation, then "as" is better. If 'o' is used just to check the type then 'is' is better.


I think both code do the same thing. I would probably use the first if I wasn't sure of the object am dealing with (for example, dynamically loading a class that's supposed to implement an interface). But will use the second if I am pretty sure (for example, finding a control on a page).


using "as" and checking for null is faster than using "is" and then casting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜