0

I dont think this is possible in c# but ill post it anyway.

Given my code

Control ctrlA = null, ctrlB = null;
var ctrlCollection = new []{ctrlA, ctrlB};
for (int i = 0; i < ctrlCollection.length;i++)
ctrlCollection[i] = new Control();

Is it possible to to construct these two objects and have them referenced to their respective variables (ctrlA and ctrlB)? As it stands, ctrlA and ctrlB will still have null references.

1
  • Are you trying to defer your object initialization? If you are on .NET 4.0+ have a look at Lazy Initialization Commented Jun 27, 2012 at 13:39

5 Answers 5

4

No, it's not. (at least, not unless you want to work with pointers or something) Will this work for you?

var ctrlCollection = new Control[2];
for (int i = 0; i < ctrlCollection.Length; i++)
    ctrlCollection[i] = new Control();
Control ctrlA = ctrlCollection[0], ctrlB = ctrlCollection[1];
Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it...I type too slow.
+1 Correct and provides a solution, too. My answer doesn't even answer the question. I should downvote myself.
2

This won't work. The collection only stores references to its content, in your case ctrlA and ctrlB. When the statement ctrlCollection[i] = new Control(); is executed, this reference is replaced by another one.

ctrlA will still point to the original ctrlA reference (being null), ctrlCollection[i] points to a newly initialized Control object.

Comments

0

This is essentially the same as explicitly defining the length of the array. There's no need to add nulls to the array and then later overwrite null with a newly instantiated Control in the array item.

var ctrlCollection = new Control[2];
for (int i = 0; i < ctrlCollection.Length; i++)
    ctrlCollection[i] = new Control();

Comments

0
var ctrlCollection = new []{ctrlA, ctrlB}; 
for (int i = 0; i < ctrlCollection.length;i++) 
{
    ctrlCollection[i] = new Control();
} 
Control ctrlA = ctrlCollection[0];
Control ctrlB = ctrlCollection[1]; 

Can't imagine why you'd want to, but this should do what I think you are asking.

Comments

0

Assuming that the size of you collection is fixed you can do this:

Control ctrlA, ctrlB;
var controls = new[] {
  ctrlA = new Control(),
  ctrlB = new Control()
};

This requires that the Control variables are declared in the same scope as the Control array is initialized.

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.