Deep C# - Inheritance |
Written by MIke James | |||||||
Monday, 27 December 2021 | |||||||
Page 3 of 3
Is and AsThere are two operators that can help avoid run-time exceptions when casting. The is operator can be used to test the type of the reference before applying a cast. For example: if (MyAnything is MyClassB) { MyClassB MyB = (MyClassB)MyAnything; }; This is the basic form of the is but as well as a type it can also test for a more general pattern – see Pattern Matching in Chapter 2. The as operator is an alternative way of writing a cast but with the difference that if it fails the reference is to null. For example: MyClassB MyB = MyAnything as MyClassB; never throws an exception but you have to make sure that you don’t end up using a null reference because it didn’t actually work. Notice that you can use as to write a cast method call more neatly: (MyAnything as MyClassB).MethodB() but notice that you will generate a run-time error if the cast fails and MethodB doesn’t exist. To avoid this you can use the null conditional operator: (MyAnything as MyClassB)?.MethodB() Now the result is a null if the method call fails. Always use as in place of explicit casting. In Chapter But Not In This Extract
PostludeInheritance is simple when you restrict it to code reuse. Unless, that is, you allow overriding existing methods as well as adding new methods. If you allow overriding then you have to make a choice about which version of the method is called – early or late binding. This is a complication that can be difficult to understand and even more difficult to keep under control. This complication is entirely due to enforcing strong typing. In a language that doesn’t assign a type to variables, only to objects, then the only possibility is late binding. Today inheritance is only partly about code reuse and abstract classes can be used to ensure that derived classes have a particular set of methods. This allows us to implement, rather than inherit the implementations of, those methods.
Deep C#Buy Now From Amazon Chapter List
Extra Material <ASIN:1871962714> <ASIN:B09FTLPTP9> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info
|
|||||||
Last Updated ( Saturday, 01 January 2022 ) |