Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to create .NET6 class with many non-nullable properties?

Tags:

c#

.net

I trying to create class with some number of non-nulable properties (>7).

If I do like this:

public class Meeting
{

    public Name Name { get; set; }
    public Person ResponsiblePerson { get; set; }
    public Description Description {get; set; }
    public Category Category { get; set; }
    public Type Type { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public List<Person> Attendees { get; set; }


    public Meeting()
    {
        Attendees = new List<Person>();
    }
}

I get warnings like this: "Non-nullable property '...' must contain a non-null value when exiting constructor. Consider declaring the property as nullable."

There is a list of variants I thinked of:

  • Default values removes this warning, but I think, that it will just add useless values, that in the future will be needed to be changed anyway.

  • If I init all properties in constructor this warning gets away, but then constructor will have >7 params which is nightmare.

  • I have seen that some people use "Builder" pattern to init classes with many params. But the builder itself can't prevent 'null' values (The builder will get same warnings).

  • There is easy way to remove warning, by making nullable property in .csproj file from true to false, but I don't want to just remove that warning. I want to make class itself safe from null values.

Whats clean way create that class?

like image 291
Yoro Avatar asked Dec 07 '25 10:12

Yoro


1 Answers

Since C#11 you can add a Required modifier.

public class Meeting
{
    public required Name Name { get; set; }
    public required Person ResponsiblePerson { get; set; }
    public required Description Description {get; set; }
    public required Category Category { get; set; }
    public required Type Type { get; set; }
    public required DateTime StartDate { get; set; }
    public required DateTime EndDate { get; set; }
    public List<Person> Attendees { get; set; } = new List<Person>();
}

This feature aims to improve how we initialize objects that do not rely on constructor parameters.

More detailed info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required

like image 161
Yoro Avatar answered Dec 09 '25 00:12

Yoro