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
}
}
You simply want to use the
Marshal.SizeOfmethod in theSystem.Runtime.InteropServicesnamespace.Do however take note of the following paragraph in the Remarks section:
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).