Solving development problems  |  About this blog

C# sizeof – Gets a size of a custom class programatically

In .NET, sizeof() works only for basic variable types, like int, double, etc. If you try to use sizeof() for a managed class then compiler reports error:

Cannot take the address of, get the size of, or declare a pointer to a managed type

Alternative to sizeof() would be System.Runtime.InteropServices.Marshal.SizeOf() but this one works with unmanaged types (not a native .NET class).

So far, a decent solution would be to serialize object into binary stream and get the stream size. Source code:

public static long SizeOf(object obj)
{
long size = 0;

try
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
BinaryFormatter objFormatter = new BinaryFormatter();
objFormatter.Serialize(stream, obj);
size = stream.Length;
}
catch (Exception ex)
{
}

return size;
}

A non-programatic alternative is to use .NET profiler to retrieve object size.

Reference: http://social.msdn.microsoft.com/forums/en-US/clr/thread/b871dee4-6eb5-4dca-be79-b9589a79f5e9/

October 5th, 2009

blog comments powered by Disqus