Created
July 14, 2014 20:01
-
-
Save jbevain/1c98d6c4a20436266565 to your computer and use it in GitHub Desktop.
SizeOf
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.Reflection.Emit; | |
static class SizeOf<TStruct> where TStruct : struct | |
{ | |
public static readonly int Value; | |
static SizeOf() | |
{ | |
var method = new DynamicMethod("", typeof(int), Type.EmptyTypes); | |
var il = method.GetILGenerator(); | |
il.Emit(OpCodes.Sizeof, typeof(TStruct)); | |
il.Emit(OpCodes.Ret); | |
var func = (Func<int>) method.CreateDelegate(typeof(Func<int>)); | |
Value = func(); | |
} | |
} | |
struct Foo | |
{ | |
public int Bar; | |
public int Baz; | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
Console.WriteLine(SizeOf<Foo>.Value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment