.NET Reflection: determine sizes of a class' fields

c#, field, reflection, sizeof

Solution

You simply want to use the `Marshal.SizeOf` method in the `System.Runtime.InteropServices` namespace.

foreach (var fieldInfo in typeof(MyClass).GetFields(BindingFlags.Instance |
    BindingFlags.Public | BindingFlags.NonPublic))
{
    Console.WriteLine(Marshal.SizeOf(fieldInfo.FieldType));
}

Do however take note of the following paragraph in the Remarks section:

The size returned is the actually the size of the unmanaged type. The unmanaged and managed sizes of an object can differ. For character types, the size is affected by the CharSet value applied to that class.

These differences are probably inconsequential though, depending on your purpose... I'm not even sure it's possibly to get the exact size in managed memory (or at least not without great difficulty).

Problem

Goal: to programmatically determine the sizes (in bytes) of the fields of a class. For example, see the comments below ... ``` class MyClass { public byte b ; public short s ; public int i ; } class MainClass { public static void Main() { foreach ( FieldInfo fieldInfo in typeof(MyClass).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ) Console.WriteLine ( fieldInfo.FieldType ) ; // output is: // System.Byte // System.Int16 // System.Int32 // desired: to include "sizeof" each type (in bytes) ... // System.Byte 1 // System.Int16 2 // System.Int32 4 } } ```

Original source