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

I'm looking to create a list of object something like below,

C#
List<MenuItem> MyMenuItems = new List<MenuItem>();

private void Form1_Load(object sender, EventArgs e)
{
    MyMenuItems.Add(new MenuItem(1, "Sales"));
    MyMenuItems.Add(new MenuItem(2, "Purchase"));
    MyMenuItems.Add(new MenuItem(3, "Stock"));
    MyMenuItems.Add(new MenuItem(4, "Deliveries"));
    MyMenuItems.Add(new MenuItem(5, "Returns"));

}


Where MyMenuItems is an object with 2 properties Id and Name.

Here in the above example while adding objects to the list I need to create a new object everytime.

I there anyway where I can reuse the object which is created only once.

The above object is a dummy object, I have an object which has 10 properties and while adding it to the list some properties may or may not be null.

I need to handle this scenario because while creating multiple objects and adding it to list a performance issue is coming up.
Posted

1 solution

You can't "reuse" an object and add it to a list:
C#
public class MyClass
    {
    public string Name { get; set; }
    public int Number { get; set; }
    public MyClass(string name) { Name = name; }
    }

C#
List<MyClass> list = new List<MyClass>();
MyClass instance = new MyClass("Joe");
instance.Number = 666;
list.Add(instance);
instance.Name = "Mike";
list.Add(instance);
foreach (MyClass mc in list) Console.WriteLine("Name: {0}, Number: {1}", mc.Name, mc.Number);
Will output:
VB
Name: Mike, Number: 666
Name: Mike, Number: 666
because the list stores a reference to the instance of the object you add, not a copy of it. (Hence a Class instance is a Reference Type - you pass around references to the object all the time).

If you want to add different objects to the list, you have to create new instances for each one you add - performance issue or not.
 
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