Inheritance question – Baseclass = new Derivedclass-Collection of common programming errors
The second explanation of Shweta Jain is little bit misleading. If base class has virtual method that derived class overrides, then derived class implementation is called not the base class implementation. Instead if base class has method that derived class shadows, then base class method is called.
So what you do is in the second line is you declare variable type of Baseclass and set its reference to Derivedclass that must inherit from Baseclass. This might not be very useful if derived type is known at compile time, but very efficient if correct derived type is known/decided at runtime for example when creating correct Baseclass implementation based on some configuration.
For example
class Program { static void Main(string[] args) { BaseClass obj = new DerivedClass(); Console.WriteLine(obj.Print()); // prints derived class Console.WriteLine(obj.Print2()); // prints base class Console.ReadKey(); } } public class BaseClass { public virtual string Print() { return "BaseClass"; } public string Print2() { return "BaseClass"; } } public class DerivedClass : BaseClass { public override string Print() { return "DerivedClass"; } public new string Print2() { return "DerivedClass"; }
}