Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are null values in C# string interpolation handled?

Tags:

c#

c#-6.0

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.

like image 440
Calle Avatar asked Mar 09 '16 15:03

Calle


People also ask

How does NULL work in C?

Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.

How is the null character represented in C?

The null character is often represented as the escape sequence \0 in source code , string literals or character constants.

IS NULL always defined as 0 in C?

No, but zero is always NULL .

Can we write NULL in C?

The Null character in the C programming language is used to terminate the character strings. In other words, the Null character is used to represent the end of the string or end of an array or other concepts in C. The end of the character string or the NULL byte is represented by '0' or '\0' or simply NULL.


2 Answers

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.

like image 171
juharr Avatar answered Sep 21 '22 12:09

juharr


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 with String.Empty.

like image 41
Soner Gönül Avatar answered Sep 20 '22 12:09

Soner Gönül