Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading