I am trying C# 8.0 out, and I want to enable the null reference checking for the entire project. I am hoping I can improve my code design, and without disabling the nullabil
While certainly highlighted due to non-nullable defaults in C# 8, this is really a common 'circular dependency' problem that has always existed with interdependent construction.
As you found, one standard solution is to use a restricted setter. With C# 8, you may want to use a 'null-forgiving' null! during deserialization of the object graph - allowing you to differentiate an unconstructed set from a valid empty set, and minimize allocation.
Example:
class Person
{
internal Person(string name, IReadOnlyList friends)
{
Name = name; Friends = friends
}
public string Name { get; }
public IReadOnlyList Friends {get; internal set;}
}
class SerializedPerson { ... }
IEnumerable LoadPeople(string path)
{
var serializedPeople = LoadFromFile(path);
// Note the use of null!
var people = serializedPeople.Select(p => new Person(p.Name, null!));
foreach(var person in people)
{
person.Friends = GetFriends(person, people, serializedPeople);
}
return people;
}