Replies: 2 comments
-
I think MemberNotNullWhenAttribute may address your scenarios adequately.
public class C
{
[MemberNotNullWhen(true, nameof(X))]
[MemberNotNullWhen(false, nameof(Y))]
public bool HasX
{
get
{
if (X != null && Y == null)
{
return true;
}
else if (X == null && Y != null)
{
return false;
}
else
{
throw new InvalidOperationException();
}
}
}
public string? X;
public string? Y;
public static void M(C c)
{
if (c.HasX)
{
c.X.ToString();
c.Y.ToString(); // warning
}
else
{
c.X.ToString(); // warning
c.Y.ToString();
}
}
}
public class C
{
[MemberNotNullWhen(true, nameof(X), nameof(Y))]
public bool HasXAndY
{
get
{
if (X != null && Y != null)
{
return true;
}
else if (X == null && Y == null)
{
return false;
}
else
{
throw new InvalidOperationException();
}
}
}
public string? X;
public string? Y;
public static void M(C c)
{
if (c.HasXAndY)
{
c.X.ToString();
c.Y.ToString();
}
else
{
c.X.ToString(); // warning
c.Y.ToString(); // warning
}
}
}
public class C
{
[MemberNotNullWhen(true, nameof(Value))]
public bool HasValue => Value != null;
public string? Value;
public void M()
{
if (HasValue)
{
Value.ToString();
}
else
{
Value.ToString();
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
Very nice, however it doesn’t solve the first sample. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Make it possible to add dependency between members similar way as you can do it for parameters using NotNullIfNotNullAttribute.
For instance either
x
ory
has value but not both:Another sample, both either null or non-null:
Also with boolean indicating nullability:
etc.
Beta Was this translation helpful? Give feedback.
All reactions