Get REAL memory usage for a type in C#

So far, the using direct IL is very seldom required with how powerful C# is. However, I found a good need: C#'s sizeof operator sucks!

So, I wrote a tiny library to use the sizeof IL instruction.

Differences:

  • Doesn't throw an error on reference types(returns size of pointer for platform)
  • Accurately gets the size of an object IN MEMORY, not just the used size of the type.
  • Has no problems dealing with mixed structs containing references and fields
  • Works exactly how you would expect it to and will work on any type

Also, the IL is extremely simple, boiling down to 2 actual instructions sizeof and ret. It also is verifiable and runs on Mono and .Net, and of course works on any platform (probably including Mono For Android and friends and compact framework?)

It's BSD licensed and here is some example code showing how to use it:

using System;

using Earlz.BareMetal;
namespace Testfoo
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine(BareMetal.SizeOf<int>());
      Console.WriteLine(BareMetal.SizeOf<string>());
      Console.WriteLine(BareMetal.SizeOf<Foo>());
      Console.WriteLine(BareMetal.SizeOf<Bar>());
      Console.ReadKey();
    }
  }
  struct Foo
  {
    int a, b;
    byte c;
    object foo;
  }
  class Bar
  {
    string foo;
    string bar;
    AssemblyLoadEventArgs meh;
    DateTime d;
  }
}

You can get the precompiled library (and see the source) at bitbucket

Posted: 11/14/2012 3:17:15 AM

Comments

Posting comments is currently disabled(probably due to spam)