0

Sometimes, when you create DTOs to deserialize json, you decorate properties with the [JsonRequiredAttribute]:

class Car
{
    [JsonRequired]
    public string Make { get; set; }
}

However, when you do this while using ReSharper or C# 8 you'll see the following warning:

Car.cs(30, 19): [CS8618] Non-nullable property 'Make' is uninitialized. Consider declaring the property as nullable.

In some projects I have a lot of such warnings and I was wondering if there is a way to suppress them only for false-positives? I could disable them completely but I'd rather not to.

t3chb0t
  • 16,340
  • 13
  • 78
  • 118
  • 1
    Can you just initialize Make to an empty string? – Michael Liu Nov 11 '19 at 15:11
  • It should be possible [to disable specific warning](https://stackoverflow.com/a/51838112/1997232) for next line using *once*, not sure in error, try `CS8618`? – Sinatr Nov 11 '19 at 15:11
  • You can try to decorate the property with `[NotNull]` attribute or init by an empty string – Pavel Anikhouski Nov 11 '19 at 15:13
  • @MichaelLiu this would look like a property had a default value. It would work for some of them but in many cases there is no resonable value I could provide. I'm not sure about that solution. It's not just a string, there can be dictionaries, lists, all kinds of stuff, also interfaces or other abstract types. – t3chb0t Nov 11 '19 at 15:14
  • Actually, it's not resharper warning, those you can disable [normally](https://stackoverflow.com/a/13726795/1997232), but that would be more work than fixing problem. – Sinatr Nov 11 '19 at 15:15

1 Answers1

4

If you are using C# 8, you could use the Null Forgiving Operator. For example,

public string Make { get; set; } = null!;

From the docs

The postfix ! operator has no runtime effect - it evaluates to the result of the underlying expression. Its only role is to change the null state of the expression, and to limit warnings given on its use.

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • I've tried this out with my `TryDoSomething` methods and this is also useful for `out T value` parameters because there the compiler also warns about possible null assignment. Or just returning `default!` in empty implementations. – t3chb0t Nov 11 '19 at 15:34