Search code examples
c#nullablec#-8.0nullable-reference-types

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?


Solution

  • 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.