using System.Reflection; using System.Runtime.CompilerServices; namespace Sandbox; public static partial class SandboxSystemExtensions { private static readonly ReflectionCache _managedSizeCache = new( ComputeManagedSize, new KeyValuePair( typeof( void ), 0 ) ); /// /// Get the managed size of a given type. This matches an IL-level sizeof(t), even if it cannot be determined normally in C#. /// Note that sizeof(t) != Marshal.SizeOf(t) when t is char or bool. /// /// /// An IL-level sizeof(t) will return sizeof(IntPtr) for reference types, as it refers to the size on stack or in an object, /// not the size on heap. /// public static int GetManagedSize( this Type t ) => _managedSizeCache[t]; private static MethodInfo _getManagedSizeHelper; private static int ComputeManagedSize( Type t ) { _getManagedSizeHelper ??= typeof( Unsafe ).GetMethod( nameof( Unsafe.SizeOf ) )!; return _getManagedSizeHelper.MakeGenericMethod( t ).CreateDelegate>()(); } }