2

I have some validation code that throws an exception if a string is null/empty/blank. I'd like for it to signal to the null checking system that argument is not null after the function returns.

void ThrowIfNullEmptyOrBlank(string? argument, string paramName)
    => ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName);

[return: NotNull] void ThrowIfNullEmptyOrBlank(string? argument, string paramName) isn't right, 'cause my method doesn't return the value (I suppose I could change that, but it's cleaner this way).

Is it possible to do what I'm trying?

Benjin
  • 2,264
  • 2
  • 25
  • 50
  • How about: string ThrowIfNullEmptyOrBlank(string? argument, string paramName) { ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName); return argument; } . The compiler will know the output is not null and you can use that – Shane Dec 06 '22 at 21:26
  • Dotnet uses the MaybeNullWhenAttribute, but that is internal – Shane Dec 06 '22 at 21:30
  • That first suggestion requires callers to set `argument` to the result of this call for the type data to propagate; I'd rather not rely on people remembering to do that. – Benjin Dec 06 '22 at 21:32
  • You might want to consider splitting the logic for "checking" the value with "throwing". `IsNullOrWhitespace` also already exists which uses `[NotNullWhen]`, which only works because the `Is...` method returns a boolean. – gunr2171 Dec 06 '22 at 21:33
  • `IsNullOrWhitespace` is actually null/empty/whitespace, which is _not_ what I'm looking for in some checks that call this. I considered giving a special condition to call that prebuilt method if all three flags are set, but decided against it. – Benjin Dec 06 '22 at 21:42

1 Answers1

2

Just use NotNullAttribute:

void ThrowIfNullEmptyOrBlank([NotNull] string? argument, string paramName)
    => ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName);

From Attributes for null-state static analysis interpreted by the C# compiler:

A nullable parameter, field, property, or return value will never be null.

Which matches the goal - argument will never be null if method returns.

This answer also can be useful (also check out the CallerArgumentExpressionAttribute trick).

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • I thought I'd tried that, but I think I'd applied the annotation to the wrong method during my checking. Thanks for making me take a second look! – Benjin Dec 06 '22 at 21:40