Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between String.Empty and “” and null? [duplicate]

Tags:

c#

.net

Possible Duplicate:
What is the difference between String.Empty and “”

Is "" equivalent to String.Empty?

Which is preferred for initializing string values?

like image 837
Joan Venge Avatar asked Jun 22 '09 16:06

Joan Venge


People also ask

What is the difference null and empty?

The main difference between null and empty is that the null is used to refer to nothing while empty is used to refer to a unique string with zero length. A String refers to a sequence of characters.

Is it better to use null or empty string?

So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

Is string empty == null?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.

Is empty string and null same in C?

They are different. A NULL string does not have any value it is an empty char array, that has not been assigned any value. An empty string has one element , the null character, '\0'. That's still a character, and the string has a length of zero, but it's not the same as a null string, which has no characters at all.


3 Answers

public sealed class String {
    //...
    public static readonly String Empty = "";
    //...
}

Use null when you want to represent that there is no value;

Use String.Empty when you want to represent that there is a value, but the value is a blank string.

like image 194
yfeldblum Avatar answered Oct 23 '22 13:10

yfeldblum


String.Empty because it is a static variable, rather than "" which has to create a new string, and null means that you must then set the string equal to a new instance of a string.

(thanks for the correction)

like image 32
CodeMonkey1313 Avatar answered Oct 23 '22 14:10

CodeMonkey1313


Yes. And String.Empty, but please don't worry about it.

The difference between String.Empty and “” are pretty small, but there is a difference. “” actually creates an object, it will likely be pulled out of the string intern pool and String.Empty creates no object, so if you are really looking for ultimate memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code…

like image 8
Matthew Flaschen Avatar answered Oct 23 '22 14:10

Matthew Flaschen