2

Recently we started to use C# nullable reference types in our projects. Of course in our project, we use nuget libraries that don't support nullable reference types.

What is the best practice of using such libraries? I'm speaking of cases like this:

public class MyClass
{
    public string myString { get; }

    public MyClass(string myString)
    {
        this.myString = myString;
    }
}

Property can be initialized with null value from external null-oblivious library. The analyzer does not warn you about this in any way. And code will throw NullReferenceException. That's why it seems to me that nullable reference types are a little bit useless. Previously we used guards to validate properties in the constructor like this:

public MyClass(string myString)
{
    if (myString == null) throw new ArgumentNullException();
    this.myString = myString;
}

Are there other defensive techniques and best practices to protect code from NullReferenceException?

Astemir Almov
  • 396
  • 2
  • 16
  • 3
    You're still allowed to use null-checkds, ***especially*** when your code is likely to be exposed to "null-oblivious" callers. But even in the general case: c#8's null reference checks are best effort, not absolute. – Marc Gravell Dec 09 '21 at 07:19
  • 2
    You MUST still include the null checks. This is not optional. You don't even need a null-oblivious library to call with null - some code could just do `var x = new MyClass(null!);` and you'd get no warning. – Matthew Watson Dec 09 '21 at 09:40
  • 2
    @MatthewWatson this is true. Exclamation mark worries me a lot. We already have code like this: `class MyClass{ string myString { get; set;} = default! }` – Astemir Almov Dec 09 '21 at 11:39

0 Answers0