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

1k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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.