6

I wonder if there is any way to write the following code a lot shorter...

public PictureBox pb1; 
public PictureBox pb2; 
public PictureBox pb3;
..... 
public PictureBox pb50;

And then, is there any way to add all those variables to a list, without having to perform the same ugly code again.

listPB.add(pb1); listPB.add(pb2);...... ListPB.add(pb50);

The method I use is really dumb and I hoped that there were some other way to do it. Thanks for the help!

1
  • why you create 50 separate instances, you can use List and its index to get particular instance Commented Apr 17, 2014 at 7:28

6 Answers 6

8

You can make an ad-hoc collection like this:

PictureBox[] pictureBoxen = {pb1, pb2, pb3, ..., pb50};

and then you can use AddRange on the list to add them

listPB.AddRange(pictureBoxen);

Or if listPB is created on that place, and only contains those variables, you could do:

List<PictureBox> listPB = new List<PictureBox>{pb1, pb2, ..., pb50};

Note that this kind of syntax was only introduced in C#3, in 2008, so it is safe to assume that you are using that or higher.

For C#2 and below, looping is the best I could come up with.

Sign up to request clarification or add additional context in comments.

Comments

2

Use a loop

for(int i = 0; i < 10; i++)
{
    PictureBox p = new PictureBox();
    listPb.Add(p);
}

Comments

2

Use this:

public PictureBox pb1,pb2,pb3,pb4....,pb50;

then

List<PictureBox> listPB = new List<PictureBox>{pb1, pb2, ..., pb50};

Comments

2

you can do this :

List<PictureBox> listPicture = new List<PictureBox>() { pb1, pb2, pb3, pb4, pb5, etc... };

Comments

1
List<PictureBox> list = new List<PictureBox>();
    for(int i = 0; i < 50; i++)
    {
    list.add(new PictureBox{
      //set properties here..
    });
    }

Comments

1

If the list is yours to initialize, I would use array in the beginning:

PictureBox[] pictures = new PictureBox[50];
for (int i = 0; i < pictures.Length; i++)
{
    pictures[i] = new PictureBox();

    // Do something else
}

If the 50 instances are generated through another way, I suggest using Notepad++ Find and Replace with Regex.

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.