Nullable reference types and MSTest ClassInitialize

Viewed 305

MSTest offers a [ClassInitialize] attribute, which can be placed on a static method to provide one-time initialization.

Assume I have a static member in a test class that I wish to initialize in such [ClassInitialize] method. How can I mark that it's not nullable?

For example, consider the following code:

private static Database _database;

[ClassInitialize]
public static void InitializeClass(TestContext testContext)
{
    _database = new Database();
}

With #nullable enable, I get a very understandable warning: CS8618 Non-nullable field '_database' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.

I could move the initialization to the constructor (but it would happen for each test method). I could use the null-forgiving operator (!). Are there better options to mark that _database is not null?

1 Answers

I prefer to use null forgiving in situations like this. Specifically, you can just set properties you know will be populated, but the compiler can't pick up using null!.

For example:

private static Database _database = null!;
Related