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...
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With