Say I have a method that starts like this, where we use a method to check for null
and other validations.
If I do that, the compiler still complains about a possible null reference exception in the lines of code that follow.
Is there a way to make it so it doesn't?
For instance, using String.IsNullOrEmpty
or String.IsNullOrWhitespace
seems to indicate to the compiler that the value has been checked.
Can I do that with my own methods?
public static void Apply(string imagePath, string texturePath, string outputPath, bool isPreviewImage, double? dpi, Color distressedColor)
{
// check each param for not null
StringParameter.ThrowIfNoValue(imagePath, nameof(imagePath));
StringParameter.ThrowIfNoValue(texturePath, nameof(texturePath));
StringParameter.ThrowIfNoValue(outputPath, nameof(outputPath));
// how do I make the compiler understand that "imagePath" cannot be null
var request = WebRequest.Create(imagePath);
}
static class StringParameter
{
// is there a way to mark this method to the compiler so it understands that the value cannot be null when use beyond this method call?
internal static void ThrowIfNoValue(string value, string name)
{
if (string.IsNullOrWhiteSpace(value ?? throw new ArgumentNullException(name)))
throw new ArgumentException("Must have a value", name);
}
}