Home > Backend Development > C++ > Can a Base Class Object Be Assigned to a Derived Class Reference in C#?

Can a Base Class Object Be Assigned to a Derived Class Reference in C#?

Barbara Streisand
Release: 2025-01-18 11:56:12
Original
818 people have browsed it

Can a Base Class Object Be Assigned to a Derived Class Reference in C#?

Assign base class object to derived class reference in C#

In C#, can I use explicit type conversion to assign a base class object to a derived class reference? Attempting to do this will result in a runtime error.

Explanation

You cannot directly assign a base class object to a derived class reference. This is because a derived class reference assumes that it points to an instance of the derived class, not a base class object. Assigning a base class object to a derived class reference can lead to inconsistent behavior and unexpected results.

Example

Consider the following code:

<code class="language-csharp">object o = new object();
string s = (string)o;
int i = s.Length;</code>
Copy after login

Attempting to access the Length property of the string variable s will result in an exception because s is actually an object, not a string.

In order to achieve conversion between base and derived classes, consider implementing a method that creates an appropriate derived type instance based on the base type. Alternatively, re-evaluate the inheritance hierarchy to eliminate the need for this conversion.

The above is the detailed content of Can a Base Class Object Be Assigned to a Derived Class Reference in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template