A more elegant way to display null?

I have a (possibly) dumb question about formatting a type mapping with a null value. At the moment, when I need to indicate that a field of null type really has a null value, I encode it as follows:

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

Or some variations of this body text.

I don’t think I can use the coalesce operator - or at least I don’t think the right approach (correct me if I am wrong).

Is there a better and effective way to do this? I just feel that this boilerplate code is increasingly infecting my codebase ...

+6
source share
2 answers

Your approach is not bad in itself, but you are right in your concern about code duplication. You can solve this by creating a helper method, for example:

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

In this example, I created an extension method, but the regular method will also work fine. Then you can only do:

 var stringToDisplay = nullableDecimal.Display(); 

... which is better to read and prevents a myriad of "N / A" in the code (and, as stated in the comments, also makes refactoring easier if ever needed).

+11
source

In C # 5 or older, your code is probably as good as it is, although you can always extract it by your own method if you sprinkled it everywhere.

Also consider stuffing "N/A" into a constant if you want to change it.

However, in C # 6, you can change it a bit, although it will not be much better:

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

The operator ?. called the null condition statement and is basically the short syntax of the expression you should have started with.

Basically, this part of the expression means the following:

 string temp = nullableDecimal != null ? nullableDecimal.ToString() : null; 

although the operator ?. will only evaluate the part before it once, not twice, so this is more like:

 var operand = nullableDecimal; string temp = operand != null ? operand.ToString() : null; 

Not very important here, but if it is a method call, it could be.

To extract it into a method, simply create an extension method:

 public static class MyNullableDecimalExtensions { public static string ToDisplayText(this decimal? value) { if (decimal.HasValue) return decimal.Value.ToString(); return "N/A"; } } 

I don’t really like the syntax of the ?: Operator, so in such a method I would write out a complete if-statement.

Then you can call it like this:

 var stringToDisplay = nullableDecimal.ToDisplayText(); 
+8
source

All Articles