Use the AS and is operators to securely cast

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.