-2

I'm trying to do something I 'm not even sure it's possible , therefore I would like to seek some suggestions.

I want to create 20 objects and each object names is assigned according to their number given. All twenty objects will be instantiated from the class called myClass, and they will have name called object_0,object_1,object_2 and so on.. with the properties i defined in the class given below. Is that possible?? Thanks

Let say i want to implement these codes, click is just like a Main void to trigger these codes

private void button_Click(object sender, EventArgs e)
{  
    for (int i = 0; i < 20; i ++)
    {
        myClass object_i = new myClass();
    }
}



public class myClass
{
    public myClass
    {

    }
}
el psy Congroo
  • 354
  • 1
  • 4
  • 19

1 Answers1

1

I dont know what you are trying to do exactly, but use a List to store your object.

var myListOfObjects = new List<MyClass>();
for (var i = 0; i < 20; i++)
{
  myListOfObjects.Add(new MyClass());
}

And if you look @ your code ... your crteated objects lifetime is only inside the Loop :)

Referencing to the comment of @Alex-k you also could use a Dictionary if you want to store the objects by key

var myDictOfObjects = new Dictionary<string, MyClass>();
for (var i = 0; i < 20; i++)
{
  myDictOfObjects.Add(string.Format("object_{0}", i), new MyClass());
}
S.L.
  • 1,056
  • 7
  • 15
  • Yes good point . THanks for your help. – el psy Congroo Aug 08 '14 at 13:21
  • where did you create an object from MyClass? – el psy Congroo Aug 08 '14 at 13:26
  • @elpsyCongroo just replace object with MyClass – S.L. Aug 08 '14 at 13:39
  • I was trying to create a list of objects, each object can take a bitmap from a file path according the the index i gave to them, for example if this object has a name object_2 , he must load 2nd picture. therefore I need to provide a function within the class, but it seems your first code is just creating a list of empty objects. – el psy Congroo Aug 11 '14 at 10:19