Search code examples
c#nullable-reference-types

Is there a way to null-annotate this return value (not null depending on arguments) or do I need to redesign?


This API definition predates nullability annotations. Is there a way to annotate this correctly or do I need to redesign the API surface?

    public static IEnumerable<DirectoryEntry> GetDirectoryContents(string path,
        NonExtantDirectoryBehavior nonExtantDirectoryBehavior = NonExtantDirectoryBehavior.Throw,
        FollowSymbolicLinks followSymbolicLinks = FollowSymbolicLinks.Never)

nonExtantDirectoryBehavior will always be a constant in the caller; GetDirectoryContents can only return null if the argument's value is ReturnNull.

I have to actually place the attributes rather than use ?, but that's a minor detail.


Solution

  • GetDirectoryContents can only return null if the argument's value is ReturnNull.

    The System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute is the closest you could get to that behavior, but it takes a boolean argument.

    If you were willing to revise the method signature to make that parameter a boolean or use a separate named method (e.g. TryGetDirectoryContents), you could probably get that kind of behavior. Otherwise, you could just note that the return value can be null in general, or leave it how it is.