AlexiAmni
AlexiAmni

Reputation: 402

Creating variable of type <derived class> to store <base class> object in C#

i have a question about practical use of this example, when you are creating a variable of type derived class to store a variable of base class object.

DerivedClass C = new BaseClass(); 

in what case i can use this.

Upvotes: 0

Views: 218

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37123

If you´re trying to cast an instance of your base-class to an instance of derived-class you have to ensure that the first actually IS a derived-type using if (obj is DerivedClass) newInstance = (DerivedClass) obj.

If you need an upcast you have to implement a kind of copying method that copies all members from your base to your derived class using reflection e.g. In this case you have to set some kind of default-value for every member of DerivedClass that is NOT part of BaseClass. But this is more a hack and might bring some danger because you may create some corrupt instances.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503469

in what case i can use this.

You can't. Ever.

The main point of static typing is so that you can rely on the value of a variable being compatible with the type you've declared. So if you declare a variable as:

DerivedClass C;

then any value for C must be able to be treated as a DerivedClass. In particular, all the members of DerivedClass must be available. That simply wouldn't be the case if the value is actually a reference to an instance of BaseClass which doesn't have all those members.

Fortunately the language rules (and therefore the compiler) understand that this would be a Very Bad Thing and so you'll get a compile-time error.

Upvotes: 2

Related Questions