Closed RobSiklos closed 1 year ago
Following will prevent the warning:
public static void RequireValidString([NotNull] string? s)
{
ThrowIfTrue(string.IsNullOrEmpty(s));
}
public static void ThrowIfTrue([DoesNotReturnIf(true)] bool isTrue)
{
if (isTrue) { throw new ArgumentException(); }
}
@RikkiGibson Is this by-design?
@Youssef1313 Yes, that will prevent the warning, but the point isn't really about the nullable check, it's about the [NotNull]
attribute on the return value causing a warning even when the method won't return.
Maybe here's a better example:
public static void RequireValidString([NotNull] string? s)
{
bool isBad = true;
ThrowIfTrue(isBad);
} // CS8777: Parameter 's' must have a non-null value when exiting.
public static void ThrowIfTrue([DoesNotReturnIf(true)] bool isTrue)
{
if (isTrue) { throw new ArgumentException(); }
}
The compiler doesn't track what possible values a bool variable could have at a given point. Therefore, we do expect a warning for the ThrowIfTrue(isBad)
case.
Thanks @RikkiGibson , that makes sense.
So what's the best way to get around this warning? Should I just suppress it locally by enclosing in a #pragma warning disable/restore
pair?
In this case, I know for a fact that the RequireValidString
method cannot exit unless s
is non-null. Is there any way for me to tell this to the compiler so it doesn't give me the warning, since it can't discover this for itself?
Is there any way for me to tell this to the compiler so it doesn't give me the warning, since it can't discover this for itself?
Debug.Assert(s is not null)
is commonly used for this.
Version Used: .NET 7.0
Steps to Reproduce:
Compile the following code:
Diagnostic ID: CS8777
Expected Behavior: No warning, because the
ThrowIfTrue
method checks the condition.Actual Behavior:
CS8777: Parameter 's' must have a non-null value when exiting.
on the last line of theRequireValidString
method.If there is a way to avoid the warning with correct code, while still keeping a similar structure, please let me know.