MuhKuh
MuhKuh

Reputation: 376

Marking C# 8 nullable reference types as "this can't be null"

I am trying the new nullable reference types C# 8.0. I have come to one tiny issue:

foreach(FileSystemAccessRule rule in directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
    // do something with rule
}

This shows a warning since the compiler thinks the rule could be null, which it never will be.

My current fix is this:

foreach(FileSystemAccessRule? rule in directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
    if (rule == null) continue;
    // do something with rule
}

But I would be much happier with a fix, like [NeverNull]FileSystemAccessRule rule or something like that. Is there a way to achieve this?

Upvotes: 3

Views: 319

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063864

if AuthorizationRuleCollection doesn't declare the nullability, or declares them as nullable: the compiler is right to complain. You can use the dammit operator, though, if you're sure:

rule!.DoTheThing();

There is an open issue (at time of writing) to perhaps change this rule slightly in the future.

Upvotes: 7

Related Questions