Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Usage patterns for the "is" keyword

Tags:

c#

c#-3.0

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.

like image 668
scope_creep Avatar asked Nov 02 '09 16:11

scope_creep


Video Answer


1 Answers

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();
}
like image 163
JaredPar Avatar answered Sep 21 '22 10:09

JaredPar