nattylife

lets say i have the following

static void Main(string[] args)
{
int[] sss = new int[5];
Console.WriteLine("size=" + sss.Length);
Console.WriteLine(sss[0] == null);
Console.WriteLine(sss[1] == null);
Console.WriteLine(sss[0]);
Console.WriteLine(sss[1]);

eee[] EEEE = new eee[10];
Console.WriteLine("size=" + EEEE.Length);
Console.WriteLine(EEEE[0] == null);
Console.WriteLine(EEEE[1] == null);
Console.ReadLine();
}


public class eee
{
public int a;
}

with ouput:
size=5
False
False
0
0
size=10
True
True

when i create an array of user defined types, do i still need to go through the array and assign each element with a reference to an instantiated object of that type i thought

eee[] EEEE = new eee[10];

would allocate the memory for all of these objects and have immediate access to them.



Re: Visual C# General creating arrays of user defined types

Mike Danes

Yes, you need ro initialize each array element to an instance of an object.

There is an exception to this if the element type of the array is a value type (bool, int, long..., enums and structs). In this case each element of the array is initialized to the default value for that type (false for bool, 0 for int and other numeric types).

If you think of it, it is the same thing as when you declare fields in a class:

public class Foo

private eee EEE; // default initialized to null

private int I; // default initialized to 0

public static void Main(string[] args) {

Console.WriteLine(EEE == null);

Console.WriteLine(I);

EEE = new eee();

I = 2;

Console.WriteLine(EEE == null);

Console.WriteLine(I);

}