Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi

How to find ,how much memory allocated for an object in our system

for example we have a class

class test
{
string name;
int number
}

test obj=new test();

For this object "obj" some what memory will be allocated in our system.How to see this allocated memory in our system
Posted
Comments
ZurdoDev 5-Nov-12 9:02am    
One way is to add up its properties.

1 solution

You can't in practical terms.
The class itself has a size, but because it contains a reference to another class (in this case a string) the size of the class is meaningless, because it will not incude the size of any possible references. While you could find out the size of the instance, that still is meaningless:
C#
[StructLayout(LayoutKind.Sequential)]
class A { public string s; int i;}
[StructLayout(LayoutKind.Sequential)]
class B { int i;}

private void button2_Click(object sender, EventArgs e)
    {
    A a = new A();
    a.s = "Hello there!";
    B b = new B();
    Console.WriteLine("A: {0}\nB: {1}", Marshal.SizeOf(a), Marshal.SizeOf(b));
    }
Will give you:
A: 8
B: 4
which is not a lot of use to anyone!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900