suppose we have this class structure:
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base class constructor has been called.");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor has been called.");
}
}
so, my question is simple: Why does C# let me to create an instance of the Base class using the constructor of the Derived Class?
for explample:
BaseClass instance = new DerivedClass();
I would also like to know what is the effect of doing it or what would the benefits be of doing that? I know that if I execute this code, the base class constructor gets called first and then the derived constructor because this follows the normal behavior of class inheritance.
thanks.
You aren’t; you’re creating an instance of
DerivedClassand storing a reference to that instance within a variable whose type isBaseClass. Any variable in C# (or virtually any object-oriented language) that is of typeTcan hold a reference (or pointer, depending on your language) to any object whose type isTor a type that derives fromTat some point.Doing this (in C#, anyway) has no effect whatsoever on how the object is constructed, so there is no “effect” in any strict sense.