Null handling the smart way

Null handling the smart way

NZ() is the best way to habdle nulls that you've never heard of!

The best C# function you've never heard of - NZ()

Are you forever checking those pesky nullable fields so you don't generate null errors?

If you come from a Microsoft Access background as I do you will be aware of some very useful Visual Basic functions such as NZ() (and DLookup() but I'll leave that one for another day)

You can use the Nz function to return zero, a zero-length string (" "), or another specified value when a Variant is Null. For example, you can use this function to convert a Null value to another value and prevent it from propagating through an expression.

Why NZ() didn't find its way into C# baffles me, it's not as if the problem went away! But it's so simple to recreate as to be laughable. so I have done it so you don't have to.

It uses the null coalescing operator ?? which allows for the selection of the first non-null value from a pair of values

It is presented as an extension method so it can be conveniently called like this.

                    ///  summary>
            ///  Always return a string, even if null is passed in.
            ///  summary>
            public static string NZ(this string str, string valueIfNull = "")
                return str ?? valueIfNull;


Nz ( variant [, valueifnull ] )

The Nz function syntax has these arguments:




Required. A variable of data type Variant.


Optional (unless used in a query). A Variant that supplies a value to be returned if the variant argument is Null. This argument enables you to return a value other than zero or a zero-length string.

Note: If you use the Nz function in an expression in a query without using the valueifnull argument, the results will be a zero-length string in the fields that contain null values.

If the value of the variant argument is Null, the Nz function returns the number zero or a zero-length string (always returns a zero-length string when used in a query expression), depending on whether the context indicates the value should be a number or a string. If the optional valueifnull argument is included, then the Nz function will return the value specified by that argument if the variant argument is Null. When used in a query expression, the NZ function should always include the valueifnull argument,

If the value of variant isn't Null, then the Nz function returns the value of variant.

The only classes I construct are in the models folder. I have very few complex C# objects like interfaces/enumerations - I'm a quick in out guy!


NZ is back - and bashing those nulls into shape!