views:

198

answers:

2

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
     }
    }
+9  A: 

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).

Noldorin
Thank you very much!
JaysonFix
+1  A: 

Note that the sum of the sizes of the fields won't total the amount of memory used by any given class instance. Alignment filler and object header information used by the CLR for various purposes, and possible associated synchronization primitives for monitor support (lock keyword in C#), won't be part of the total.

Barry Kelly
This is absolutely true - there is no easy way (I'm not sure there's *any* way) to get the actual size of a class in memory. However, I think the OP is just interested in the sizes of the individual fields.
Noldorin
Certainly no fully portable way, the best would be an estimation based on the relationship between process memory and number of instances. However, with questions like this one - sizes of fields - I usually end up with suspicions. It sounds dodgy from the outset... :)
Barry Kelly
@Barry: Yeah, exactly... you're getting into murky territory there.
Noldorin