What’s the preferred way of checking if the value is null?
Let’s say we have some entity, which has properties, which can be null (some of them or all of them).
And I wish to check this in runtime, if some property is actually null or not.
Would you use simple Entity.Property != null check in this case or would you implement a specific method, let’s say like
bool HasProperty() {
return Property != null;
}
What would you choose and why?
For property values which can be
null, my preference is to do the followingnullHasand the rest containing the original property name which determines if the other property is non-nullnullIn this example it would be
The reasoning behind this is that C# does not have a standard way of describing whether or not a value can be null. There are many different conventions and techniques avalaible but simply no standard. And not understanding the
nullsemantics around a value leads to missednullchecks and eventuallyNullReferenceExceptions.I’ve found the best way to express this is to make the
nullfeature of a property explicit in the type itself by adding theHasproperty if and only if the property can benull. It’s not a perfect solution but I’ve found it works well in large projects.Other solutions I’ve tried
Maybe<T>orOption<T>type in the flavor of F#. This works but I find I receive a lot of push-back from developers who’ve never done functional programming and it leads to a rejection of the idea entirely in favor of #1.