When starting the program

class Program { static void Main() { string[] listNames = new string[4] { "Личный", "Рабочий", "Семейный", "Список книг" }; TodoList[] TodoLists = new TodoList[listNames.Length]; for (int i = 0; i < TodoLists.Length; i++) { TodoLists[i].name = listNames[i]; } } } class TodoList { public string name; public string[] tasks; } 

getting an error

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at dz.Program.Main(String[] args) in C:\Users\Yuri\source\repos\dz\dz\Program.cs:line 15

    2 answers 2

    TodoList[] TodoLists = new TodoList[listNames.Length] only creates an array on the listNames.Length elements, in each cell of which lies a null .

    You first need to initialize the elements of the array to work with them.

     TodoList[] TodoLists = new TodoList[listNames.Length]; for (int i = 0; i < TodoLists.Length; i++) { TodoLists[i] = new TodoList(); TodoLists[i].name = listNames[i]; } 
       for (int i = 0; i < TodoLists.Length; i++) { TodoLists[i] = new TodoList() { name = listNames[i] }; }