Skip to content

Instantly share code, notes, and snippets.

@xoofx
Created September 27, 2015 13:20
Show Gist options
  • Save xoofx/b7bc54a6c71628bbbe93 to your computer and use it in GitHub Desktop.
Save xoofx/b7bc54a6c71628bbbe93 to your computer and use it in GitHub Desktop.
Struct inheritance test program in C# (related article on http://xoofx.com/blog/2015/09/27/struct-inheritance-in-csharp-with-roslyn-and-coreclr/)
using System;
public struct ValueBase
{
public int A;
public int B;
public int Calculate()
{
return this.A + this.B;
}
}
public struct ValueDerived : ValueBase
{
public int C;
public new int Calculate()
{
return base.Calculate() + C;
}
}
public class Program
{
public static int StaticCalculateByRefBase(ref ValueBase value)
{
return value.A + value.B;
}
public static int StaticCalculateOnBase(ValueBase value)
{
return value.A + value.B;
}
static void Assert(string context, int value, int expected)
{
Console.WriteLine(context + " = {0}, expect = {1}, {2}", value, expected, value == expected ? "Ok" : "Error");
}
public unsafe static void Main(string[] args)
{
var valueDerived = new ValueDerived();
// Object initializer is not supported in this example, so we initialize fields directly
valueDerived.A = 1;
valueDerived.B = 3;
valueDerived.C = 5;
// Check memory layout.
var ptr = (int*)&valueDerived;
Assert("valueDerived.A", valueDerived.A, ptr[0]);
Assert("valueDerived.B", valueDerived.B, ptr[1]);
Assert("valueDerived.C", valueDerived.C, ptr[2]);
// Call the Calculate method on derived struct
Assert("valueDerived.Calculate()", valueDerived.Calculate(), 1 + 3 + 5);
// Call the Calculate method on base struct
var valueBase = (ValueBase)valueDerived;
Assert("valueBase.Calculate()", valueBase.Calculate(), 1 + 3);
// Call a static method with by ref to base type
var result1 = StaticCalculateByRefBase(ref valueDerived);
Assert("StaticCalculateByRefBase(ref valueDerived)", result1, 1 + 3);
// Call a static method with cast to base type (no cast will generate an error)
var result2 = StaticCalculateOnBase((ValueBase)valueDerived);
Assert("StaticCalculateOnBase((ValueBase)valueDerived)", result2, 1 + 3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment