Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndreyAkinshin/95ebe7ce5b964fc6930c to your computer and use it in GitHub Desktop.
Save AndreyAkinshin/95ebe7ce5b964fc6930c to your computer and use it in GitHub Desktop.
Create derived class for base class with private constructor
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