Array Initialization:
Initialization is almost always required for an array. There are two popular ways for array initializing.Way 1 : Putting values inside curly braces
int[] myArray = new int[]{-1,-1,-1,-1,-1};
Way 2 : Using Loop
int[] myArray = new int[5];
for (int i = 0; i < myArray.Length; i++)
myArray[i] = -1;
Way 1 is fine for small size array. But if the array size is bigger, it is not the comfortable way.
Problem for Static Array:
The problem for static array is- when you declare/define it in class, you cannot use loop statement. So, it is not possible to initialize array in 2nd way. Even you cannot initialize static array in constructor, as accessing static attribute does not require constructing any object.
Solution:
Fortunately, it is possible through another static function which returns an array. Of course, that array is initialized inside that function. The following code might help you understand the trick.
public class MyClass
{
public static int[] staticArray = GetInitializedStaticArray();
public static int[] GetInitializedStaticArray()
{
int[] myArray = new int[5];
for (int i = 0; i < myArray.Length; i++)
myArray[i] = -1;
return myArray;
}
}
0 Comments:
Post a Comment