They are different as others already answered.
static void Main(string[] args)
{
string s1 = null;
string s2 = string.Empty;
string s3 = "";
Console.WriteLine(s1 == s2);
Console.WriteLine(s1 == s3);
Console.WriteLine(s2 == s3);
}
Results:
- false - since null is different from string.empty
- false - since null is different from ""
- true - since "" is same as string.empty
The problem with managing empty string vs. null strings is becoming a problem when you need to either persist it into a flat file or transfer it through communications, So I find it might be useful for other who visit this page to give a nice solution to that particular problem.
For the purpose of saving strings into a file or communications:
you will probably want to convert the string into bytes.
a good practice I recommend is to add 2 segments of header bytes to your converted string.
segment 1 - meta info which is stored in 1 byte and describes the length of the the next segment.
segment 2 - holds the length of the string to be saved.
example:
string "abcd" - to simplify I'll convert it using ASCII encoder and will get {65,66,67,68}.
calculate segment 2 will yield 4 - so 4 bytes are the length of the converted string.
calculate segment 1 will yield 1 - as just 1 byte was used to hold the length information of the converted string information (which was 4, i.e. if it was 260 I would get 2)
The new stripe of bytes will now be {1,4,65,66,67,68} which can be saved to a file.
The benefit in respect to the subject is that if I had an empty string to save I would get from conversion an empty array of bytes in the length of 0 and after calculating the segments I will end up having {1,0} which can be saved and later on loaded and interpreted back into an empty string.
On the other hand if I had null value in my string I would end up having just {0} as my byte array to save and again when loaded can be interpreted back to null.
There are more benefits such as knowing what the size to be loaded or accumulate if you jag multiple strings.
Back to the subject - it will.. well kind of pollute the stack as the same principals described are being used by any system to differentiate nulls from empty.. so yes string.Empty does take more memory than null, though I wouldn't call it pollution.. it just 1 more byte.