Is it possible to mark a property of a parameter as null/not null after a function returns?
Asked Answered
H

1

7

If I have a function bool Foo(string? input), then I can annotate it to indicate that if the return is true then input is not null:

public static bool Foo([NotNullWhen(true)] string? input)

Is it possible to do that (or something similar) for a property of an argument? I'm thinking something along the lines of

public class AClass { string? NullableString {get;set;}}
public static bool Foo([PropertyNotNullWhen(true, nameof(AClass.NullableString))] AClass input)

I don't think MemberNotNullWhen will work in this case, because it only applies to methonds, properties, and indexers and not the arguments to them.

Hardener answered 27/11, 2020 at 11:51 Comment(2)
This isn't possible at the moment. I would recommend opening a discussion on github.com/dotnet/csharplang/discussions/new with your real world example. I think this is definitely something that they will consider for a future language version if there's enough need.Caseous
@YairHalberstadt Looks like that is indeed the answer - I'll give you the tick if you post it as one. I opened an issue over at github.com/dotnet/roslyn/issues/49640 , if you're interested.Hardener
Q
3

It seems that C# added support for this:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis

In your case you need NotNullWhen

Attribute Category Meaning
AllowNull Precondition A non-nullable parameter, field, or property may be null.
DisallowNull Precondition A nullable parameter, field, or property should never be null.
MaybeNull Postcondition A non-nullable parameter, field, property, or return value may be null.
NotNull Postcondition A nullable parameter, field, property, or return value will never be null.
MaybeNullWhen Conditional postcondition A non-nullable argument may be null when the method returns the specified bool value.
NotNullWhen Conditional postcondition A nullable argument won't be null when the method returns the specified bool value.
NotNullIfNotNull Conditional postcondition A return value, property, or argument isn't null if the argument for the specified parameter isn't null.
MemberNotNull Method and property helper methods The listed member won't be null when the method returns.
MemberNotNullWhen Method and property helper methods The listed member won't be null when the method returns the specified bool value.
DoesNotReturn Unreachable code A method or property never returns. In other words, it always throws an exception.
DoesNotReturnIf Unreachable code This method or property never returns if the associated bool parameter has the specified value.
Quahog answered 24/2, 2023 at 17:50 Comment(1)
NotNullWhen does not solve the posed problem. It handles the case of specifying input will be non-null, but not input.NullableString.Volga

© 2022 - 2024 — McMap. All rights reserved.