[Proposal] MemberNotNullWhenMemberAttribute for Property and Field #122741
-
|
Usage like this: public class Item: IDisposable {
public bool IsDisposed;
public bool IsLoaded;
[MemberNotNullWhenMember(nameof(IsDisposed),false)]
public int? Id;
[MemberNotNullWhenMember([(nameof(IsDisposed),false),(nameof(IsLoaded),true)])]
public List<string>? Resource;
...
}If this is done, we can have better code analysis in the situation below: public List<string>? UseResource(Item item) {
if(item is {IsDisposed:false,IsLoaded:true}) {
return item.Resource; //No null reference warning now.
}
...
}I'm not sure if it should have two overloads, one that receives a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
It's correct to ask at csharplang. The current practice is to use [MemberNotNullWhen(true, nameof(Id))]
public bool IsDisposed;
public string? Id;Conjunction of multiple properties is unlikely to be supported because of the logical complexity. |
Beta Was this translation helpful? Give feedback.
It's correct to ask at csharplang.
The current practice is to use
MemberNotNullWhenon the condition property:Conjunction of multiple properties is unlikely to be supported because of the logical complexity.
Moreover, it's not the recommended practice to mark the nullability for invalid state. Usage of disposed/uninitialized object should be undefined or always throwing.