Home > Enterprise >  How to annotate a C# function to say that a parameter is not null if it returns
How to annotate a C# function to say that a parameter is not null if it returns

Time:12-07

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?

CodePudding user response:

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).

  • Related