Richard Ward
Richard Ward

Reputation: 459

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

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.

Upvotes: 7

Views: 2717

Answers (1)

superjugy
superjugy

Reputation: 354

Edit: I don't think you can annotate such that a property is not null. But that seems more like an encapsulation problem. Without more details it is hard to give a more precise answer, but maybe return another object that doesn't have nullable properties from that method instead or something?


Original Answer:

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.

Upvotes: 4

Related Questions