[API Proposal]: NotAllNullAttribute (or ExactlyOneNotNullAttribute) #9072
Replies: 2 comments 2 replies
-
Independently to the static analysis, you state that "exactly one of them were non-null" but then your example means "at least one" so this class Person
{
public Name? FirstName{ get; set; }
public Name? Nickname { get; set; }
public Name Name => Name. FromEither(FirstName, Nickname);
}
sealed record Name
{
private string _name { get; }
private Name(string value)
=> _name = value;
public static Name FromEither(
Name? firstName,
Name? nickname,
[CallerArgumentExpression("firstName")] string? firstNameArg = null,
[CallerArgumentExpression("nickname")] string? nicknameArg = null)
{
if ((firstName is not null) ^ (nickname is null))
{
throw new ArgumentException($"Either {firstNameArg} or {nicknameArg} must be null, but not both.");
}
return firstName ?? nickname!;
}
public static implicit operator Name(string value)
{
ArgumentException.ThrowIfNullOrEmpty(value);
return new Name(value);
}
public override string ToString() => _name;
} |
Beta Was this translation helpful? Give feedback.
-
In your examples they are technically reachable at runtime as nothing seems to be enforcing that. I would consider something like: string name = this.FirstName ?? this.Nickname ?? throw new System.Diagnostics.UnreachableException(); |
Beta Was this translation helpful? Give feedback.
-
Background and motivation
NotNullWhenAttribute
is great. I don't need to add the null-forgiving operator (!
) to suppress CS8602 Possible dereference of null in the following code:Today, I noticed a C# class where there were two nullable reference type properties. Our business logic requires that exactly one of them were non-null. Therefore, if one of them is null, the other must be non-null. However, there is no built-in attribute to annotate this relationship at compile time.
I'm curious if it's possible to do this without a null-forgiving operator.
API Proposal
(I think both
NotAllNullAttribute
andExactlyOneNotNullAttribute
will be useful.)API Usage
Alternative Designs
No response
Risks
No response
Beta Was this translation helpful? Give feedback.
All reactions