Safe Typecasting of Base Class Objects to Derived Class References in C#
Directly casting a base class object to a derived class reference in C# is risky and often leads to runtime exceptions. This is because a derived class reference expects an object of its own type or null.
Illustrative Example:
<code class="language-csharp">object o = new object(); string s = (string)o; // This will throw an exception at runtime</code>
Attempting to access derived class members after this unsafe cast will result in an error:
<code class="language-csharp">int i = s.Length; // Runtime exception: InvalidCastException</code>
The o
variable holds a base class object, incompatible with derived class members like Length
.
To prevent runtime errors, always verify the object's actual type before casting. The is
operator and pattern matching provide safe alternatives:
<code class="language-csharp">object o = new object(); if (o is string str) { int i = str.Length; // Safe access to Length } else { // Handle the case where o is not a string } // Or using pattern matching: if (o is string s2) { int length = s2.Length; }</code>
Alternatively, re-evaluate your class design. If frequent casting between base and derived classes is necessary, it might indicate a flaw in the inheritance hierarchy. Refactoring to eliminate the need for such casts is often a better solution. Consider using interfaces or composition instead of inheritance if appropriate.
The above is the detailed content of How to Safely Typecast Base Class Objects to Derived Class References in C#?. For more information, please follow other related articles on the PHP Chinese website!