In class Microsoft.Net.Http.Headers.ContentRangeHeaderValue, there is a nullable value type property (long?) that is decorated with a NotNullIfNotNull attribute referencing itself (property Length).
[NotNullIfNotNull(nameof(Length))]
public long? Length { get; private set; }
What is the purpose of this attribute in the context of a value type and what is the difference to simply omitting the attribute declaration?
CodePudding user response:
According to the definition: A return value, property, or argument isn't null if the argument for the specified parameter isn't null.
The use-case scenario:
Sometimes the null state of a return value depends on the null state of one or more arguments. These methods will return a non-null value whenever certain arguments aren't null. To correctly annotate these methods, you use the NotNullIfNotNull attribute.
Examples or code snippets can be found here.
CodePudding user response:
I think I slowly get an idea what problem this declaration attempts to solve:
The property could write the value it receives to a different variable than the one that is returned (using a property like this)
[NotNullIfNotNull(nameof(Length))]
public long? Length {
get { return _length }
private set { _anotherLength = value }
}
or simply ignore the value in the setter or do some other strange things, the attribute is needed to tell the analyzer the value given to the setter does indeed set the variable returned in the getter.
