Last active
July 29, 2016 08:31
-
-
Save AndreyAkinshin/95ebe7ce5b964fc6930c to your computer and use it in GitHub Desktop.
Create derived class for base class with private constructor
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
using System; | |
using System.Runtime.InteropServices; | |
class Program | |
{ | |
public class Base | |
{ | |
private Base() | |
{ | |
} | |
public int Value; | |
public void HelloWorld() | |
{ | |
Console.WriteLine("Hello world!"); | |
} | |
} | |
public class DerivedClassEmulator | |
{ | |
private const int MaxInstanceSize = 1024; | |
public byte[] Buffer = new byte[MaxInstanceSize]; | |
public void HelloWorld() | |
{ | |
} | |
} | |
public class Derived : Base | |
{ | |
private Derived(int n) | |
: this(n.ToString()) | |
{ } | |
private Derived(string s) | |
: this(42) | |
{ } | |
public int Value2; | |
} | |
public static class DerivedCreator | |
{ | |
[StructLayout(LayoutKind.Explicit)] | |
public struct HelpStruct | |
{ | |
[FieldOffset(0)] | |
public DerivedClassEmulator Emulator; | |
[FieldOffset(0)] | |
public Derived Derived; | |
} | |
public static Derived Create() | |
{ | |
return new HelpStruct { Emulator = new DerivedClassEmulator() }.Derived; | |
} | |
} | |
static void Main() | |
{ | |
Derived d = DerivedCreator.Create(); | |
d.Value = 1; | |
d.Value2 = 2; | |
Console.WriteLine(d.Value); // 1 | |
Console.WriteLine(d.Value2); // 2 | |
d.HelloWorld(); // Hello world! | |
Base b = d; | |
Console.WriteLine(b.Value); // 1 | |
b.HelloWorld(); // Hello world! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment