I use this type of construct often.
response = new LocationResponse ();
response.LocationDetails = new LocationDetail[4];
response.LocationDetails[0] = new LocationDetail();
response.LocationDetails[0].site = "ABCDE";
...
The piece I don't fully understand is this piece:
response.LocationDetails[0] = new LocationDetail();
Why does each individual element of the array have to be instantiated?
If you leave it out, you get undefined exceptions.
Well if an array elements were automatically instantiated, you would be locked into which classes you defined the array with. You wouldn't be able to use arrays of abstract classes or interfaces or any object which doesn't have a default constructor. This is just naming a few problems with automatically instantiating objects in an array.
You don't need to instantiate LocationDetail if it is a value type (struct). You have to instantiate it if it's a class because the default value for a reference type is null.
This code works:
public struct LocationDetail
{
private string site;
public string Site
{
get { return site; }
set { site = value; }
}
}
static void Main(string[] args)
{
LocationResponse response = new LocationResponse();
response.LocationDetails = new LocationDetail[4];
response.LocationDetails[0].Site = "ABCDE";
Console.Write(response.LocationDetails[0].Site);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With