Caerulius
Caerulius

Reputation: 425

Taking arbitrary list of objects and initializing all of them

        bgList.Add(bg1);
        bgList.Add(bg2);
        bgList.Add(bg3);
        bgList.Add(bg4);
        bgList.Add(bg5);

        //Initialize all background objects
        for (int i = 0; i < bgList.Count; i++)
        {
            bgList[i] = new Sprite();
            bgList[i].Scale = 2.0f;
        }

Is this a legitimate way to do this? Basically, the question boils down to "Can I initialize a list of objects using a for loop?

I'm getting "This Object will never not be null" warnings on the bg1, bg2, bg3, bg4, and bg5 objects, and that's making me wonder if this technique isn't allowed.

Upvotes: 0

Views: 114

Answers (2)

Sina Iravanian
Sina Iravanian

Reputation: 16296

These statements are not equivalent:

bg1 = new Sprite();

and

bgList.Add(bg1);
bgList[0] = new Sprite();

The latter will not assign the reference to the new instance to bg1. It just stores the new instance in the 0th location.

So using a collection and loop to instantiate a number of variables is not a working short-cut. You have to instantiate each variable explicitly, or use an array or collection from the first place.

Upvotes: 2

Maximc
Maximc

Reputation: 1762

a foreach would be easier for sure, and y you should be able to do it, but imo you can also add the items in the loop something like.

  for (int i = 0; i < bgList.Count; i++)
        {
            var bglistitem = new Sprite()
            bhlistitem.Scale = 2.0f;
            bgList.Add(bglistitem);
        }

Upvotes: 0

Related Questions