1. Is checks whether the object is compatible with the given type
@ 1 check whether the object is an instance or inherited from the parent class
If (students is person)
{
... // Code
}
@ 2 is operator only consider packing, unpacking, and reference conversion;
@ 3 anonymous methods are not allowed on the left side of the is Operator (except for lambda expressions)
Ex:
View code
1 int A = 10; 2 object OBJ = A; 3 if (obj is int) 4 {5 console. writeline ("boxing... "); 6} 7 A = 20; 8 console. writeline ("A = {0}", a); 9 console. writeline ("OBJ = {0}", OBJ); 10 11 12 // output result: 13 boxing... 14 A = 2015 OBJ = 10
II. The as operator is used to convert compatible types
@ 1 The as operator is similar to type conversion. The difference is that if the as operator fails to be converted, no error is returned, but a null value is returned;
@ 2 The as operator only performs conversion by referencing, earning, and packing. The as operator cannot perform conversion by definition;
View code
1 object[] obj=new object[5]; 2 obj[0] = new MyClass(); 3 obj[1] = "hello"; 4 obj[2] = 123; 5 obj[3] = null; 6 obj[4] = 'a'; 7 for (int i = 0; i < obj.Length; i++) 8 { 9 string s = obj[i] as string;10 if(s!=null)11 {12 Console.WriteLine(s);13 }14 else15 {16 Console.WriteLine("not string ...");17 }18 }