Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Why do you need to instantiate each array element?

Tags:

arrays

c#

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.

like image 350
rbrayb Avatar asked Nov 29 '22 00:11

rbrayb


2 Answers

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.

like image 75
kemiller2002 Avatar answered Nov 30 '22 14:11

kemiller2002


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);
}
like image 28
Michael Meadows Avatar answered Nov 30 '22 15:11

Michael Meadows