Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does appending to a null string work in C#?

Tags:

string

c#

.net

null

I was surprised to see an example of a string being initialised to null and then having something appended to it in a production environment. It just smelt wrong.

I was sure it would have thrown a null object exception but this greatly reduced example also works:

string sample = null; sample += "test"; // sample equals "test" 

*Note the original code I found sets a string property to null and appends to it elsewhere so answers involving the compiler optimizing out the null at compile-time are irrelevant.

Can someone explain why this works without error?

Follow-up:

Based on Leppie's answer I used Reflector to see what is inside string.Concat. It is now really obvious why that conversion takes place (no magic at all):

public static string Concat(string str0, string str1) {     if (IsNullOrEmpty(str0))     {         if (IsNullOrEmpty(str1))         {             return Empty;         }         return str1;     }     if (IsNullOrEmpty(str1))     {         return str0;     }     int length = str0.Length;     string dest = FastAllocateString(length + str1.Length);     FillStringChecked(dest, 0, str0);     FillStringChecked(dest, length, str1);     return dest; } 

**Note: the specific implementation I was investigating (in the .Net library by Microsoft) does not convert to empty strings as is suggested by the C# standards and most of the answers, but uses a few tests to shortcut the process. The end result is the same as if it did but there you go :)

like image 232
Gone Coding Avatar asked Oct 31 '11 12:10

Gone Coding


People also ask

Can you append to a null string?

If you append a null value to the StringBuilder object, it would be stored as a “null” (four character string) in the object instead of no value at all.

Can you set a string to null in C?

C strings are null-terminated. As long as you only use the functions assuming null-terminated strings, you could just zero the first character.

What is null string how it works in string in C?

Advertisements. Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello".

What happens if string in is null?

Example using a null check Very often in programming, a String is assigned null to represent that it is completely free and will be used for a specific purpose in the program. If you perform any operation or call a method on a null String, it throws the java. lang. NullPointerException.


2 Answers

the + operator for strings are just shorthand for string.Concat which simply turns null arguments into empty strings before the concatenation.

Update:

The generalized version of string.Concat:

public static string Concat(params string[] values) {     int num = 0;     if (values == null)     {         throw new ArgumentNullException("values");     }     string[] array = new string[values.Length];     for (int i = 0; i < values.Length; i++)     {         string text = values[i];         array[i] = ((text == null) ? string.Empty : text);         num += array[i].Length;         if (num < 0)         {             throw new OutOfMemoryException();         }     }     return string.ConcatArray(array, num); } 
like image 132
leppie Avatar answered Oct 05 '22 20:10

leppie


The relevant citation should be ECMA-334 §14.7.4:

String concatenation:

string operator +(string x, string y); string operator +(string x, object y); string operator +(object x, string y);   

The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string operand is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

like image 38
Rasmus Faber Avatar answered Oct 05 '22 18:10

Rasmus Faber