C#: Getting size of a value-type variable at runtime?
Following on from Cory's answer, if performance is important and you need to hit this code a lot then you could cache the size so that the dynamic method only needs to be built and executed once per type:
int x = 42;
Console.WriteLine(Utils.SizeOf(x)); // Output: 4
// ...
public static class Utils
{
public static int SizeOf<T>(T obj)
{
return SizeOfCache<T>.SizeOf;
}
private static class SizeOfCache<T>
{
public static readonly int SizeOf;
static SizeOfCache()
{
var dm = new DynamicMethod("func", typeof(int),
Type.EmptyTypes, typeof(Utils));
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Sizeof, typeof(T));
il.Emit(OpCodes.Ret);
var func = (Func<int>)dm.CreateDelegate(typeof(Func<int>));
SizeOf = func();
}
}
}
To find the size of an arbitrary variable, x
, at runtime you can use Marshal.SizeOf:
System.Runtime.InteropServices.Marshal.SizeOf(x)
As mentioned by dtb, this function returns the size of the variable after marshalling, but in my experience that is usually the size you want, as in a pure managed environment the size of a variable is of little interest.