I know languages such as C and C++ allow determining the size of data (structs, arrays, variables...) at runtime using sizeof() function. I tried that in C# and apparently i
public static class TypeSize
{
public static int GetSize(this T value)
{
if (typeof(T).IsArray)
{
var elementSize = GetTypeSize(typeof(T).GetElementType());
var length = (value as Array)?.GetLength(0);
return length.GetValueOrDefault(0) * elementSize;
}
return GetTypeSize(typeof(T));
}
static ConcurrentDictionary _cache = new ConcurrentDictionary();
static int GetTypeSize(Type type)
{
return _cache.GetOrAdd(type, _ =>
{
var dm = new DynamicMethod("SizeOfType", typeof(int), new Type[0]);
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Sizeof, type);
il.Emit(OpCodes.Ret);
return (int)dm.Invoke(null, null);
});
}
}