10.6 The is operator (Java's instanceof operator)C#'s is operator is used to determine if the runtime type of an object is equivalent to another, much like how Java's instanceof is used. It goes like this: <expression> is <type> The is operator returns a boolean result ( true or false ). The is operator returns true if:
Let's study an example. The output is shown as comments. For convenience, the inheritance relations between the classes in this example are shown in Figure 10.2. 1: using System; 2: 3: interface ITest1 {} 4: interface ITest2 {} 5: class GrandParent:ITest1{} 6: class Parent:GrandParent {} 7: 8: class Child: Parent,ITest2 { 9: public static void Main(){ 10: 11: Child c = new Child(); 12: Console.WriteLine(c is Child); // True 13: Console.WriteLine(c is ITest1); // True 14: Console.WriteLine(c is ITest2); // True 15: Console.WriteLine(c is Parent); // True 16: Console.WriteLine(c is GrandParent); // True 17: 18: Parent p = new Parent(); 19: Console.WriteLine(p is Child); // False 20: Console.WriteLine(p is ITest1); // True 21: Console.WriteLine(p is ITest2); // False 22: Console.WriteLine(p is Parent); // True 23: Console.WriteLine(p is GrandParent); // True 24: 25: ITest2 it2 = new Child(); 26: Console.WriteLine(it2 is Child); // True 27: Console.WriteLine(it2 is ITest1); // True 28: Console.WriteLine(it2 is ITest2); // True 29: Console.WriteLine(it2 is Parent); // True 30: Console.WriteLine(it2 is GrandParent); // True 31: } 32: } Figure 10.2. Class diagram showing inheritance relations between the classes in this example.
Compilation warning: [View full width]
The compilation warnings warn that some of the statements containing the is operator can already be determined during compile time. Output: c:\expt>test True True True True True False True False True True True True True True True If you want to perform a cast of <expression> to <type> if (<expression> is <type>) , C# has a convenient as operator which you can use. |