tags:

views:

41

answers:

2

I just have a general .NET inquiry:

Suppose I have a large (memory size) Class

public class BigClass
{
...
}

If I add an item to an ItemControl such as a ListBox or Datagrid like this

BigClass b = new BigClass();
ListBox1.Items.Add(b);

How is the resource usage in doing something like this? Is the added item referenced or is a copy made of the instance (causing a lot of memory usage)?

Thanks.

+3  A: 

It will be added as a reference. There are no implicit copy semantics for .NET objects.

Volte
You are right , but that doesn't mean that There is no Clone in the "add" method of the ListBox.Items
A: 

Just to be sure , I Just made a quick and dirty test , ListBox1.Items doesn't make a copy but rather keep a reference.

Here is the complete code :

public class A
{

    int a;

    public int A1
    {
        get { return a; }
        set { a = value; }
    }

}
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        A a = new A();
        a.A1 = 4;

        A b = new A();
        b.A1 = 4;

        listBox1.Items.Add(a);
        listBox1.Items.Add(b);

        A c = listBox1.Items[0] as A;
        A d = listBox1.Items[1] as A;

        if(a.Equals(c))
        {
            int k = 8; //program enter here so a is instance of c
        }

        if (a.Equals(d))
        {
            int k = 8; //program doesn't enter here meaning a is not instance of d
        }


    }
}
Thanks, that's very helpful to be sure.
AdamD