Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.
I have tried it and it creates a run-time error.
Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.
I have tried it and it creates a run-time error.
I know this is old but I've used this successfully for quite a while.
You can do this using generic.
You get three benefits using this approach.
No it is not possible, hence your runtime error.
But you can assign an instance of a derived class to a variable of base class type.
As many others have answered, No.
I use the following code on those unfortunate occasions when I need to use a base type as a derived type. Yes it is a violation of the Liskov Substitution Principle (LSP) and yes most of the time we favor composition over inheritance. Props to Markus Knappen Johansson whose original answer this is based upon.
This code in the base class:
Allows:
Since it uses reflection, it is "expensive". Use accordingly.
Not only explicit, but also implicit conversions are possible.
C# language doesn't permit such conversion operators, but you can still write them using pure C# and they work. Note that the class which defines the implicit conversion operator (
Derived
) and the class which uses the operator (Program
) must be defined in separate assemblies (e.g. theDerived
class is in alibrary.dll
which is referenced byprogram.exe
containing theProgram
class).When you reference the library using the Project Reference in Visual Studio, VS shows squiggles when you use the implicit conversion, but it compiles just fine. If you just reference the
library.dll
, there are no squiggles.Another solution is to add extension method like so:
then have a constructor in each derived class that accepts base class:
It will also optionally overwrite destination properties if already set (not null) or not.