Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A more elegant way to display null?

Tags:

c#

nullable

I have a (probably) dumb question about display formatting of nullable types. At the moment, when I need to indicate that a field of a nullable type does indeed have a null value, I code it like this:

var stringToDisplay = nullableDecimal.HasValue ? nullableDecimal.ToString() : "N/A";

Or some variation of that basic text.

I don't think I can use a coalesce operator - or at least I don't think that's the right approach (correct me if I'm wrong).

Is there a better and more efficient way to do this? I just feel like this boilerplate code is infesting my codebase more and more these days...

like image 335
code4life Avatar asked Sep 22 '15 13:09

code4life


1 Answers

Your approach isn't bad per se, but you are right about your worry for code duplication. You can solve this by creating an auxiliary method, such as:

public static class DecimalExtensions
{
    public static string Display(this decimal? value) 
    {
        return value.HasValue ? value.ToString(): "N/A";
    }
}

In this example I have created an extension method but a regular method would also work just fine. Then you can do just:

var stringToDisplay = nullableDecimal.Display();

...which is nicer to read and prevents the myriad of "N/A"s in the code (and as stated in the comments, also eases refactoring if ever needed).

like image 114
Konamiman Avatar answered Oct 15 '22 22:10

Konamiman