Skip to content

Instantly share code, notes, and snippets.

@jbevain
Created July 14, 2014 20:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbevain/1c98d6c4a20436266565 to your computer and use it in GitHub Desktop.
Save jbevain/1c98d6c4a20436266565 to your computer and use it in GitHub Desktop.
SizeOf
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