Normally you cannot get the size of an object in the managed heap. This is because that size doesn't make sense in the managed world due to different reasons. One of them could be that the size of the same object is not guaranteed to be the same between two starts of the application. The JIT compiler is free to layout the objects as it sees fit. The layouting can be different due to different configuration of the machine, different version of the CLR, etc. Furthermore, your type may reference other reference types. Even two objects can cross-reference the same object. How can you possibly tell what is the size of the object Using Marshal.SizeOf returns the size of the marshaled (unmanaged)
equivalent of the provided type. I said "normally" back then because there is an operator that returns the managed size for a type (only for valuetypes). In C# it is represented by the *sizeof* operator. However *sizeof* operator has some limitations in addition to its syntax I don't think that is what you need.
About sizeof operator you can read at MSDN
ms-help://MS.MSDNQTR.2003FEB.1033/csref/html/vclrfSizeofPG.htm
To demonstrate the difference between Marshal.SizeOf and *sizeof* operator run the following simple code
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
unsafe static void Main(string[] args)
{
Console.WriteLine("Managed size: {0}", sizeof(char));
Console.WriteLine("Unmanaged size: {0}", Marshal.SizeOf(typeof(char)));
Console.ReadLine();
}
}
The result is:
Managed size: 2
Unmanaged size: 1
Unmanaged size is 1 because System.Char struct is set to be marshaled as ANSI char by default.