0
class City
{
    string name;

    public string getName()
    {
        return name;
    }

    public void setName(String value)
    {
        name = value;
    }
}

static void Main(string[] args)
{
    City[] arr = new City[1];
    arr[0].setName("New York");
}

The problem is that I get "System.NullReferenceException", "Object reference not set to an instance of an object." at the line where I set the name to New York. If I do:

City city = new City();
city.setName("New York");

I don't get any errors but I want to use an array, since I will be adding more objects. Is this possible in C# because it is in C++? Is the only way to declare 5 objects, set their names and then create an array and put them inside?

user2765257
  • 29
  • 2
  • 6

2 Answers2

4

You are creating an empty array. You have to initialise the object before assigning it:

City[] arr = new City[1];
arr[0] = new City();
arr[0].setName("New York");
Ludovic Feltz
  • 10,872
  • 3
  • 48
  • 57
  • Thanks. Guess it's some sort of saving memory, to not declare all the objects unless I actually declare and use them. – user2765257 Dec 04 '14 at 15:36
  • @user2765257 It's because sometimes an empty constructor doesn't exist on class you want to put in an array. That's why you have to call it manually. – Ludovic Feltz Dec 04 '14 at 15:38
1

This line just creates an array with one element.

City[] arr = new City[1];

The element is null.

You need to assign it a value

arr[0] = new City();

Then you can access it.

arr[0].setName("New York");
Ben Robinson
  • 21,319
  • 5
  • 61
  • 78