-
Say I have this (simplified) code: public static class Guard
{
[ContractAnnotation("value:null => halt")]
public static void IsNotNull<T>([ValidatedNotNull] T value, string paramName)
{
if (value is null)
{
throw new ArgumentNullException(paramName);
}
}
}
public static class SecureStringHelper
{
public static string ToStringSecure<T>(T value)
{
Guard.IsNotNull(value, nameof(value));
if (value is SecureString)
{
return "<masked>";
}
return value.ToString(); // gives: CS8602: Dereference of a possibly null reference.
}
} In the method This is because the compiler doesn't know that Is there a way to communicate this behavior to the C# compiler? Other code flow analysis tools can already do this:
I know I could write |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Yes, via the |
Beta Was this translation helpful? Give feedback.
Yes, via the
NotNull
attribute on thevalue
parameter. See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis#specify-post-conditions-maybenull-and-notnull