Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

is

The is operator is used to check whether the run-time type of an object is compatible with a given type. The is operator is used in an expression of the form:

expression is type

Where:

expression
An expression of a reference type.
type
A type.

Remarks

An is expression evaluates to true if both of the following conditions are met:

  • expression is not null.
  • expression can be cast to type. That is, a cast expression of the form (type)(expression) will complete without throwing an exception. For more information, see 7.6.6 Cast expressions.

A compile-time warning will be issued if the expression expression is type is known to always be true or always be false.

The is operator cannot be overloaded.

Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.

Example

// cs_keyword_is.cs
// The is operator
using System;
class Class1 
{
}

class Class2 
{
}

public class IsTest 
{
   public static void Test (object o) 
   {
      Class1 a;
      Class2 b;

      if (o is Class1) 
      {
         Console.WriteLine ("o is Class1");
         a = (Class1)o;
         // do something with a
      }
      
      else if (o is Class2) 
      {
         Console.WriteLine ("o is Class2");
         b = (Class2)o;
         // do something with b
      }
      
      else 
      {
         Console.WriteLine ("o is neither Class1 nor Class2.");
      }
   }
   public static void Main() 
   {
      Class1 c1 = new Class1();
      Class2 c2 = new Class2();
      Test (c1);
      Test (c2);
      Test ("a string");
   }
}

Output

o is Class1
o is Class2
o is neither Class1 nor Class2.

See Also

C# Keywords | typeof | as | Operator Keywords

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft