0

I would like to create multiple objects/instances in a loop. how to do this?

class lh 
    {
        public string name;

        public lh(string name)
        {
            this.name = name; ;
        }

    }

while((line = ps.ReadLine()) !=null)
{
      lh a = new lh(line);
}

obviously I can't create a new object using the same name (a) over and over again

4 Answers 4

5
List<lh> objects = new List<lh>();

while(your_condition)
{
    objects.Add(new lh(line));
}
Sign up to request clarification or add additional context in comments.

Comments

3

How about a list or array?

List<lh> lines = new List<lh>();

while((line = ps.ReadLine()) !=null)
{
    lines.Add(new lh(line));
}

Comments

3

You could add your instances to a list:

List<lh> lhs = new List<lh>();
while ((line = ps.ReadLine()) != null)
    lhs.Add(new lh(line));

Comments

2
var list = new List<lh>();
while((line = ps.ReadLine()) !=null)
{
    list.Add(new lh(line));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.