DEV Community

Cover image for Yo, Yo, Check Null

Yo, Yo, Check Null

Haiyang Wang on June 20, 2020

It is a very common practice to check for null in parameters: public void DoSomething(Foo foo) { if (foo is null) { throw new Arg...
Collapse
 
sam_ferree profile image
Sam Ferree

I like the readability of that API

Minor suggestion, use “argument is null” instead of “argument == null”

The == operator can be overloaded and we can’t guarantee the overload null checks it’s arguments.

Collapse
 
callmewhy profile image
Haiyang Wang

Thanks Sam! I just updated the sample code with 'is null'. You are totally right.

Collapse
 
peledzohar profile image
Zohar Peled

Just one note: You want the actual name of the parameter to show in the exception, not the type name, so you need to change the signature to IsNull<T>(T argument, string argumentName) and call it like this:
ThrowIf.Argument.IsNull(foo, nameof(foo)).
Also, you're adding one more method call to the stacktrace, but that's really not a big deal, though.

See fiddle.

Collapse
 
callmewhy profile image
Haiyang Wang

Yes you are right. I noticed it days ago and wanted to fix this today before anyone discovering the mistake. Then your comment comes LOL

We can fix this by ThrowIf.Argument.IsNull(foo, nameof(foo)), but foo, nameof(foo) is really redundant. I want to get the caller params name in callee directly and I found this: Proposal: Caller Parameter Name #1557. We can get the caller member name, line number, and the file path, but we cannot get the caller's params name.

For now, ThrowIf.Argument.IsNull(foo, nameof(foo)) may be the only way to display the name of params

Thanks for calling out! I just updated the blog according to your suggestion.

Collapse
 
dmerejkowsky profile image
Dimitri Merejkowsky

Impressive quality for a first blog post! Congrats and welcome.

Collapse
 
amul047 profile image
amul047

Check this out, just came out infoq.com/news/2020/06/CSharp-9-Null/

Collapse
 
callmewhy profile image
Haiyang Wang

Great! I am really looking forward to the new features in C# 9

Collapse
 
sunilmusinada profile image
sunilmusinada

I like it. Couldn’t it be better if we use nameof instead of passing the argument.

Collapse
 
callmewhy profile image
Haiyang Wang • Edited

Thanks, I just removed the hardcode params name and use nameof instead. It will be perfect if we can get the caller's params name in callee method. According to Proposal: Caller Parameter Name #1557 it's not possible for now.