namespace Demo{class A{public A(){System.Console.WriteLine("This is a {0},", this.GetType());}}
class B : A{}
// . . .
B b = new B(); // Output: "This is a Demo.B"}
public class MyClass{private IDependency _myDependency;
public MyClass(IDependency someValue = null){_myDependency = someValue ?? GetDependency();}
// If this were static, it could not be overridden// as static methods cannot be virtual in C#.protected virtual IDependency GetDependency(){return new SomeDependency();}}
public class MySubClass : MyClass{protected override IDependency GetDependency(){return new SomeOtherDependency();}}
public interface IDependency { }public class SomeDependency : IDependency { }public class SomeOtherDependency : IDependency { }
public class BadBaseClass{protected string state;
public BadBaseClass(){this.state = "BadBaseClass";this.DisplayState();}
public virtual void DisplayState(){}}
public class DerivedFromBad : BadBaseClass{public DerivedFromBad(){this.state = "DerivedFromBad";}
public override void DisplayState(){Console.WriteLine(this.state);}}
public class BetterBaseClass{protected string state;
public BetterBaseClass(){this.state = "BetterBaseClass";this.Initialize();}
public void Initialize(){this.DisplayState();}
public virtual void DisplayState(){}}
public class DerivedFromBetter : BetterBaseClass{public DerivedFromBetter(){this.state = "DerivedFromBetter";}
public override void DisplayState(){Console.WriteLine(this.state);}}
public class Parent{public virtual object Obj{get;set;}public Parent(){// Re-sharper warning: this is open to change from// inheriting class overriding virtual memberthis.Obj = new Object();}}
public class Program{public static void Main(){var child = new Child();// anything that is done on parent virtual member is destroyedConsole.WriteLine(child.Obj);// Output: "Something"}}