Ravenix Ravenix - 2 months ago 25
C# Question

C# initializer null pointer

Currently doing some homework on C# basics. I'm getting a null pointer on this line and can't figure out what's caussing it.:

List<Project> projecten = new List<Project>{
new Project {
name = "project a",
deelnemers =
{
new Person { name = "Ed" },
new Person { name = "Mike" },
}
},
new Project {
name = "project b",
deelnemers = {
new Person {name = "Max" },
new Person {name = "Peter" },
}
}
};


the person and project classes are defined correctly I think:

public class Project
{
public string name { get; set; }
public List<Person> deelnemers {get; set;}
}

public class Person
{
public string name { set; get; }
}


It's probably something stupid but I don't see it.

The complete file is this:

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

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{

// Maak een collection mbv initializers van minimaal 3 projecten met meerdere projectleden

List<Project> projecten = new List<Project>{
new Project {
name = "project a",
deelnemers =
{
new Person { name = "Xanvier" },
new Person { name = "Jantje" },
}
},
new Project {
name = "project b",
deelnemers = {
new Person {name = "Pietje" },
new Person {name = "Keesje" },
}
}
};
List<Int16> p = new List<Int16> { 1,2,3 };
//var projectje = new Project{ name = "project a" };

}
}

public class Project
{
public string name { get; set; }
public List<Person> deelnemers {get; set;}
}

public class Person
{
public string name { get; set; }
}
}

Answer

This part is a collection initializer:

deelnemers =
    {
        new Person { name = "Ed" },
        new Person { name = "Mike" },
    }

This is perhaps one of the most confusing forms of syntax in C#. It does not initialize your list. It only calls Add on it. You need to initialize the List as well:

deelnemers = new List<Person> {
    new Person { name = "Xanvier"},
    //
}

Or, you can initialize the List in the constructor of Project. That way, your original code will work as expected.

Comments