Reputation: 29
public Tiles[,] tiles;
Is a global variable, an array, I dare say, the size of which is yet to be discovered. That's why I wish to initialize it inside a function. Alas, after the function is done, so is the variable. How doth one fix that?
Upvotes: 1
Views: 118
Reputation: 61349
If you wrote something like this:
public void Init()
{
tiles = new Tiles[2, 5];
}
The instantiated array still exists. Because it was stored in the tiles
variable, which is in the class scope, it's lifetime is that of the object. Thus, you have nothing to worry about. Subsequently accessing the tiles
field (should have been a property...) will use the object created in Init
.
As an aside, that variable is not global, it is scoped to the class. Aside from statics, there is no such thing as a "global" variable in C# (and even static members are still scoped to their class, which does have a global instance).
Note
Jon Skeet's answer indicates excellent practice for initializing variables, among other things. I am primarily trying to address the misunderstanding of variable scope/lifetime in this answer.
Upvotes: 2
Reputation: 1500385
Sounds like you just want:
private readonly Tile[,] tiles = InitializeTileArray();
...
private static readonly Tile[,] InitializeTileArray()
{
Tile[,] array = ...;
// Whatever you want here
return array;
}
Note that the method has to be static - you can't call an instance method from a field initializer. If you need to do that, you need to put the call into your constructor instead.
Note that I've made the field itself private - and readonly, which may not be appropriate for you. I would recommend always (or at least nearly always) using private fields - you can expose the data via properties and indexers.
Upvotes: 1