Last active
December 11, 2015 00:19
-
-
Save martynchamberlin/4515705 to your computer and use it in GitHub Desktop.
In C#, all constructors in polymorphism will fire, starting at the top of the tree and working down. Sometimes this isn't the desired behavior. Here's a potential workaround using a simple Window Console application.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ConsoleApplication2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
B myObj = new B(); | |
// comment the next line to disable parent constructor | |
myObj.Initialize(); | |
} | |
} | |
class A | |
{ | |
public A() | |
{ | |
Type t =this.GetType(); | |
if (t == typeof(A)) | |
{ | |
/* Notice that our constructor merely invokes a method. | |
* This ensures that no code is limited to instantiation. | |
*/ | |
this.Initialize(); | |
} | |
} | |
public void Initialize() | |
{ | |
/* Here's where the real "constructing" happens. Since it's | |
* a regular method, we can call it any time we want - we're | |
* not dependent on instantiation. | |
*/ | |
Console.WriteLine("A"); | |
} | |
} | |
class B : A | |
{ | |
public B() | |
{ | |
Console.WriteLine("B"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment