Reputation: 25141
Im almost certain this defies the basic laws of C#, but is it possible to construct an 'array' or 'collection' of items by reference?
Failing that, is there any other way to construct the checkboxes in a parametered static method?
Hopefully my psuedocode makes sense (everything concerning Construct2
)
CheckBox cb = null, cb2 = null;
Main()
{
Construct(ref cb);//works
Construct2(new []{ref cb, ref cb2});//isnt going to work!
}
static void Construct(ref CheckBox cb){
cb = new CheckBox();//works
}
static void Construct2(CheckBox[] cbs) { //
cbs[0] = new CheckBox();
cbs[1] = new CheckBox();
//for (int i = 0; i < cbs.Length;i++){
// cbs[i] = new CheckBox();
//}
}
Upvotes: 1
Views: 82
Reputation: 7592
I do not believe this is possible in C#. In order to use pointers you have to declare your code within an unsafe
context, and compile the application with /unsafe
. However, this would only work for a value type such as a struct and would not work for managed objects (which is Checkbox
and most everything you would probably use).
Upvotes: 1
Reputation: 152521
Failing that, is there any other way to construct the checkboxes in a parametered static method?
Yes, have the method return an array of checkboxes instead of trying to pass in a reference.
static CheckBox[] Construct2()
{
//....
}
Upvotes: 1
Reputation: 50114
You can't pass an array of ref
variables like that. If you want to be able to construct "into" multiple variables like that I think you'll need to pass in setters of some kind:
void Construct2 (params Action<Checkbox>[] cbas)
{
foreach (var cba in cbas) cba(new Checkbox());
}
Construct2(
(c) => cb = c,
(c) => cb2 = c);
Upvotes: 3