How to get object size in memory?

Lukas Šalkauskas picture Lukas Šalkauskas · Mar 3, 2009 · Viewed 292k times · Source

I need to know how much bytes my object consumes in memory (in C#). for example how much my Hashtable, or SortedList, or List<String>.

Answer

Rush Frisby picture Rush Frisby · Jul 4, 2010

this may not be accurate but its close enough for me

long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(s, o);
    size = s.Length;
}