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?

ivanpop
  • 27
  • 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
  • 11,416
  • 4
  • 47
  • 63
  • Thanks. Guess it's some sort of saving memory, to not declare all the objects unless I actually declare and use them. – ivanpop 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,601
  • 5
  • 62
  • 79