0

How to calculate a class instance size in memory? I want to compare two class instance in size, the size that they take in ram. What should I do?

void Main()
{
    var foo1 = new Foo();
    foo1.A = 1;
    foo1.B = "A";
    foo1.C = 2;
    foo1.D = "B";

    var foo2 = new Foo();
    foo2.A = 1;
    foo2.B = "AB";
    foo2.C = 2;
    foo2.D = "CD";

    // Get the size of foo1 & foo2 and compare them to each other.
}

class Foo
{
    public int A { get; set; }
    public string B { get; set; }
    public int C { get; set; }
    public string D { get; set; }
}
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93

1 Answers1

1

Check this Link

long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(s, o);
    size = s.Length;
}
Community
  • 1
  • 1
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60