C# How to find the size of a reference type

10,521

Hmmm. I'd be using a profiling tool, but I guess something like this might work:

long before = System.GC.GetTotalMemory(true);
Foo instance = new Foo();
long after = System.GC.GetTotalMemory(true);
long consumed = after - before;
Share:
10,521
Doctor Jones
Author by

Doctor Jones

I'm a Software Developer. At the moment I primarily develop Desktop applications with WFP, and web applications using Web API, and a variety of frontend technologies. I love to experiment with and learn about new technologies. I also enjoy reading a fair number of tech blogs. I am a firm believer in continual learning and really enjoy software developement. Sites: My personal blog Twitter Here's a small list of my time sinks extra curricular activities that I do in my personal time. Sim Racing Archery Baking Brewing (Cider, Beer) I play in a band called 7 Second Hurricane, check out our music on Spotify, Amazon, iTunes, Google play music, or search for us on your favourite music platform.

Updated on June 04, 2022

Comments

  • Doctor Jones
    Doctor Jones almost 2 years

    I was wondering if there is a way to find the size of a reference type in C#. I've done some Googling and the general idea on the forums seem to be that this isn't possible. I thought I'd ask you guys and see if anyone here knew better.

    After all, profiling tools must have a way of doing this? I know it isn't usual to need to know this information, but it would be useful to have in some situations.

  • user1068352
    user1068352 almost 10 years
    What's the reason for down vote?
  • Alex
    Alex almost 9 years
    This will only measure the size of an new, empty object and does not reflect the actual memory consumption of a existing one. There also may be a accuracy-problem in multi-threaded solutions.