Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize several global variables using an array

Tags:

c#

Lets say I have the class

class Foo
{
    public int Value { get; set; }
}

And I have the global variables:

public static Foo A1 { get; set; }
public static Foo A2 { get; set; }
public static Foo A3 { get; set; }
public static Foo A4 { get; set; }
// etc... more

The following code will not set the value of those global variables:

var elementsToSet = new Foo[]{A1,A2,A3,A4}; 

for (var i = 0; i < elementsToSet.Length; i++)            
       elementsToSet[i] = new Foo {Value = i};

In other words A1 == null is true :(

I am trying to initialize A1, A2, etc not the array


how can I prevent having to do:

A1 = new Foo { Value = 1 };
A2 = new Foo { Value = 2 };
A3 = new Foo { Value = 3 };
A4 = new Foo { Value = 4 };
// etc...

PS

I know I can have an array as my global variable instead of several. I am just asking this question to learn. I have the reference of each variable. I want to set a new variable of the same type at that address.

Also

If Foo will have been a struct instead of a reference type (class) this will work no?

like image 424
Tono Nam Avatar asked Feb 15 '26 07:02

Tono Nam


1 Answers

The reason is that your array elementsToSet at first contains four instances of null (because A1, A2, ... A4 are all null originally). Then when you set each of elementsToSet[i] to a new Foo(...) the elements in the array are set, but none of the elements are references to your A1 ... A4 Foos.

Really, the best ways to do this are

  1. Initialize each Foo, one per line. This can get annoying if you have a lot of them.
  2. Have your global variables be in an array, and then loop through and initialize.
  3. Use reflection (the worst idea).

Edit for the question's edit: No, your original code will still not work if Foo is a struct instead of a class, because then setting the elementsToSet[i], even when elementsToSet is initialized with A1 ... A4, will still just set the elements in the array. Even more so, the original A1 ... A4 are not being set through the array.

like image 131
Jashaszun Avatar answered Feb 16 '26 20:02

Jashaszun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!