C# – Ignore the Nullable CS8618 warning in DTO classes

When you have the Nullable Reference Types feature (Nullable for short) enabled, one of the warnings you’ll run into is the following: CS8618 Non-nullable property X must contain a non-null value when exiting constructor.

This warning doesn’t make sense in a very common scenario:

  • You have a DTO class with a non-nullable reference type, such as a string.
  • It’ll definitely be populated with a value from the data and won’t be null.
  • Therefore, you know you don’t need to set an initial value for the property.

You can just ignore the warning when it applies to DTOs. This saves you the needless effort of trying to “fix” this non-issue with something like the following:

public class Coder
    public string Name { get; set; } = null!;
Code language: C# (cs)

Yes, this does make the warning go away, but it’s pretty pointless. Furthermore, you probably have lots of DTOs with lots of properties, which means you’ll keep running into this problem and have to “fix” it over and over. Better to save the effort and ignore it. I’ll show two options below.

Option 1 – Only suppress the warning for DTO classes

You might want to only suppress the warning for DTO classes. The reason is because you might find it helpful for pointing out potential problems in non-DTO classes. So this is a targeted approach – you’re keeping the good and throwing out the bad.

One way to disable the warning for your individual DTO classes is by using a pragma, like this:

#pragma warning disable CS8618
public class Coder
    public string Name { get; set; }
    public string Language { get; set; }
    public string Project { get; set; }
#pragma warning restore CS8618
Code language: C# (cs)

Note: Depending on your project structure and naming conventions, you may be able to use an editorconfig file to suppress the warnings for all DTOs by using a pattern. Use with caution, since this has the risk of inadvertently suppressing the warning for non-DTO classes that happen to match the pattern.

Option 2 – Suppress the warning at the project level

If you don’t find this warning helpful at all, you can suppress it at the project level with the NoWarn setting:

<Project Sdk="Microsoft.NET.Sdk">


Code language: HTML, XML (xml)

This is also a useful approach if a project only contains DTO classes.

Don’t disable Nullable warnings

I wouldn’t suggest disabling Nullable warnings at the file level, like this:

#nullable disable warnings
public class Coder
    public string Name { get; set; }
Code language: C# (cs)

Why not? Because this is disabling ALL Nullable warnings in the file, instead of just disabling the specific warning you don’t want. If you happen to add logic to this file at some point (instead of just having auto properties), that logic wouldn’t be checked for Nullable problems.

Leave a Comment