简体   繁体   中英

C# Usage patterns for the “is” keyword

Whats the common and not so common usage patterns for the C# keywork 'is'. I recently used it to count the number of used cells in a typed array, (still stuck at the bottom with xsd generated classes, as xsd2code had a number of problems with IETF designed schema, hence no generics).

What other common and more importantly common usage patterns are offered.

The 'is' keyword is useful for determine if an object is convertible to a type via a reference, boxing or unboxing conversion (C# lang spec 7.9.10). It is similar to 'as' except that it doesn't actually do the conversion, merely return if it is possible.

It is useful in any scenario where knowing if an object is convertible to a type is useful but having the object via a reference to that type is not necessary.

if ( o is SomeType ) {
  TakeSomeAction();
}

If having a reference of the specified type to the value is useful then it's more efficient to use the 'as' operator instead.

// Wrong
if ( o is SomeType ) {
  SomeType st = (SomeType)o;
  st.TakeSomeAction();
}

// Right
SomeType st = o as SomeType;
if ( st != null ) {
  st.TakeSomeAction();
}

Actually, I almost never use it. When I need it, it's usually because I'm going to cast the value to the required type anyway, so I prefer to use as instead.

Compare :

if (x is MyType)
{
    MyType y = (MyType)x;
    ...
}

And :

MyType y = x as MyType;
if (y != null)
{
    ...
}

In the first case : 2 operations (1 type check + 1 cast)

In the second case : 1 operation (type check + cast in one shot)

I can't remember ever used is . Most of the time, if you need to know if an instance is of a certain type, you need to use it as such.

So I usually directly cast it using as or explicit casting if I'm sure that it actually is of the type in question.

I try to write code that it does not need to cast or find type information more then once. So writing is before a cast of a reference type is certainly not recommendable.

With the upcoming v4 instead of using is and as there's a different possible approach.

void somemethod(dynamic o)
{
DoStuff(o);
}

DoStuff(neededType o){}
DoStuff(object o){}

that however might have a performnce hit but makes for nice readability

It depends if you need a reference to the type if it is a type of the given type. If it is then you should use the `as keyworkd.

MyObject mo = obj as MyObject;
if (mo == null) {
    // do something.
} else {
    // do something else.
}

which would yield a reference which you can test for null. Otherwise, using the as oprator you'' end up being require to perform a cast anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM