Reputation: 1800
In C# 6.0, string interpolations are added.
string myString = $"Value is {someValue}";
How are null values handled in the above example? (if someValue
is null)
EDIT: Just to clarify, I have tested and am aware that it didn't fail, the question was opened to identify whether there are any cases to be aware of, where I'd have to check for nulls before using string interpolation.
Upvotes: 99
Views: 31637
Reputation: 61
It seems that the behavior depends on which underlying formatting methods are called, and the implementation of these can change over time. If you get a null formated into the string such as "(null)", it is not sure this will stay the same over several years. In some newer version of .NET it can start throwing an exception.
So I think the most safe approach is to make some condition to avoid using the null. Write a simple ternary operation like:
int? someValue = 5;
var valueStr = (someValue is not null) ? someValue.ToString() : string.Empty;
var myString = $"Value is {valueStr}";
It is an extra line of code, but at least the behavior is controlled.
Upvotes: 2
Reputation: 32296
That's just the same as string.Format("Value is {0}", someValue)
which will check for a null
reference and replace it with an empty string. It will however throw an exception if you actually pass null
like this string.Format("Value is {0}", null)
. However in the case of $"Value is {null}"
that null
is set to an argument first and will not throw.
Upvotes: 71
Reputation: 98810
From TryRoslyn, it's decompiled as;
string arg = null;
string.Format("Value is {0}", arg);
and String.Format
will use empty string for null
values. In The Format method in brief section;
If the value of the argument is
null
, the format item is replaced withString.Empty
.
Upvotes: 32