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();