Because the object is polymorphic, a variable of the base class type can hold the derived type. To access a method of a derived type, you need to cast the value back to the derived type. However, in these cases, only a simple cast attempt will cause the risk of invalidcastexception to be raised. This is why C # provides the IS and as operators. You can use these two operators to test whether a cast succeeds without the risk of throwing an exception. Generally, the as operator is more efficient because it actually returns a cast value if the cast can be successful. The IS operator returns only one Boolean value. Therefore, if you want to determine only the type of an object without actually casting it, you can use the IS operator.
The following example shows how to use the IS and as operators to cast from one reference type to another without the risk of throwing an exception. This example also shows how to use a nullable value type for the as operator.
classsafecasting {classAnimal { Public voidEat () {Console.WriteLine ("Eating."); } Public Override stringToString () {return "I am an animal."; } } classMammal:animal {}classGiraffe:mammal {}classSuperNova {}Static voidMain () {safecasting app=Newsafecasting (); //Use the was operator to verify the type. //before performing a cast.Giraffe g =NewGiraffe (); App. Useisoperator (g); //Use the As operator and test for null//before referencing the variable.app. Useasoperator (g); //Use the As operator to test//An incompatible type.SuperNova sn =NewSuperNova (); App. Useasoperator (SN); //Use the As operator with a value type. //Note the implicit conversion to int?//The method body. inti =5; App. Useaswithnullable (i); DoubleD =9.78654; App. Useaswithnullable (d); //Keep the console window open in debug mode.System.Console.WriteLine ("Press any key to exit."); System.Console.ReadKey (); } voidUseisoperator (Animal a) {if(A ismammal) {Mammal M=(mammal) A; M.eat (); } } voidUseasoperator (Objecto) {mammal M= O asmammal; if(M! =NULL) {Console.WriteLine (m.tostring ()); } Else{Console.WriteLine ("{0} is not a mammal", O.gettype (). Name); } } voiduseaswithnullable (System.ValueType val) {int? j = Val as int?; if(J! =NULL) {Console.WriteLine (j); } Else{Console.WriteLine ("Could not convert"+val. ToString ()); } } }
Use the AS and is operators to securely cast