[This is preliminary documentation and subject to change]
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
An is expression evaluates to true if both of the following conditions are met:
(type)(expression)
will complete without throwing an exception.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.
// 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"); } }
o is Class1 o is Class2 o is neither Class1 nor Class2.
C# Keywords | typeof | as | Operator Keywords