Created
July 29, 2016 15:03
-
-
Save binki/d0cd500817e25150259ec5f749fc00ca to your computer and use it in GitHub Desktop.
C# static initializers don’t care about inheritance
This file contains hidden or 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
Sub1 | |
Accessed Sub1Value: | |
Sub2 | |
Base | |
Accessed Sub2Value: | |
SubInstantiable | |
BaseInstantiable | |
Instantiated SubInstantiable: StaticInitializationInheritance.SubInstantiable |
This file contains hidden or 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
// Apparently, accessing a static member of a subclass does not initialize | |
// the static members of the base class unless you explicitly cause this to | |
// happen. | |
using System; | |
namespace StaticInitializationInheritance | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine($"Accessed {nameof(Sub1.Sub1Value)}: {Sub1.Sub1Value}"); | |
Console.WriteLine($"Accessed {nameof(Sub2.Sub2Value)}: {Sub2.Sub2Value}"); | |
Console.WriteLine($"Instantiated {nameof(SubInstantiable)}: {new SubInstantiable()}"); | |
} | |
} | |
class Base | |
{ | |
public static object BaseValue { get; } | |
static Base() | |
{ | |
Console.WriteLine(nameof(Base)); | |
} | |
} | |
class Sub1 : Base | |
{ | |
public static object Sub1Value { get; } | |
static Sub1() | |
{ | |
Console.WriteLine(nameof(Sub1)); | |
} | |
} | |
class Sub2 : Base | |
{ | |
public static object Sub2Value { get; } | |
static Sub2() | |
{ | |
Console.WriteLine(nameof(Sub2)); | |
Sub2Value = BaseValue; | |
} | |
} | |
// What about object initialization? | |
class BaseInstantiable | |
{ | |
static BaseInstantiable() | |
{ | |
Console.WriteLine(nameof(BaseInstantiable)); | |
} | |
} | |
class SubInstantiable | |
: BaseInstantiable | |
{ | |
static SubInstantiable() | |
{ | |
Console.WriteLine(nameof(SubInstantiable)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment