'C# From user input to vector with class object

Okey. so I created a class in a seperate file that looks like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class City
{
    public string name { get; set; }
    public int temp { get; set; }
}

Now I want to set values (from user input) in each element of this new vector.

City[] Cities = new City[4];
for (int i = 0; i < Cities.Length; i++)
{    
            
    Console.Write("Name of city:");
    Cities[i].name = Console.ReadLine();


    Console.Write("Temperature:");
    string strTemp = Console.ReadLine();
    Cities[i].temp = Convert.ToInt32(strTemp); 
}  

but when I reach:

Cities[i].name = Console.ReadLine();

I get this messege:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.



Solution 1:[1]

Calling new City[4]; isn't enough to instantiate each instance in the array. It simply creates an empty, or null, element in the array. You still have to instantiate the instance.

Try this:

City[] Cities = new City[4];
for (int i = 0; i < Cities.Length; i++)
{
    Cities[i] = new City();
    
    Console.Write("Name of city:");
    Cities[i].name = Console.ReadLine();


    Console.Write("Temperature:");
    string strTemp = Console.ReadLine();
    Cities[i].temp = Convert.ToInt32(strTemp);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Enigmativity