I have a centralized method for checking results from a repository. This includes a check if the Entity
property is null.
Sadly this has the annoying side-effect of showing a compiler warning, since there is no null check in the method that contains the call.
This is probably a long shot, but is there a way to tell the compiler to treat my method like a manual null check? I would prefer not to disable the warning globally, since it is actually pretty useful. Are there any other workarounds for this?
public Group GetGroup(Group.GroupId groupId)
{
if (groupId.Value == null || groupId.Is(0))
throw new Exception("Can not get group with ID: null/0");
EntityInteractionResult<Group> readResult = _groupRepository.ReadById((ulong)groupId.Value);
readResult.ValidateSuccessAndEntity(); // <- This checks if Entity is null
return readResult.Entity; // <- CS8603 possible null reference return
}
CodePudding user response:
If ValidateSuccessAndEntity
is method of EntityInteractionResult
then you can use MemberNotNullAttribute
to list members which won't be null when the method returns:
public class Result
{
public string? Value { get; set; }
public Result()
{
}
[MemberNotNull(nameof(Value))]
public void Validate()
{
if(Value is null)
throw new Exception();
}
}
var result = new Result();
result.Validate();
var c = result.Value[1]; // "warning CS8602: Dereference of a possibly null reference" if previous line commented out
Read more: