In .NET, what is the difference between String.Empty
and \"\"
, and are they interchangable, or is there some underlying reference or Localization i
Coming at this from an Entity Framework point of view: EF versions 6.1.3 appears to treat String.Empty and "" differently when validating.
string.Empty is treated as a null value for validation purposes and will throw a validation error if it's used on a Required (attributed) field; where as "" will pass validation and not throw the error.
This problem may be resolved in EF 7+. Reference: - https://github.com/aspnet/EntityFramework/issues/2610 ).
Edit: [Required(AllowEmptyStrings = true)] will resolve this issue, allowing string.Empty to validate.
Use String.Empty
rather than ""
.
This is more for speed than memory usage but it is a useful tip. The
""
is a literal so will act as a literal: on the first use it is created and for the following uses its reference is returned. Only one instance of""
will be stored in memory no matter how many times we use it! I don't see any memory penalties here. The problem is that each time the""
is used, a comparing loop is executed to check if the""
is already in the intern pool. On the other side,String.Empty
is a reference to a""
stored in the .NET Framework memory zone.String.Empty
is pointing to same memory address for VB.NET and C# applications. So why search for a reference each time you need""
when you have that reference inString.Empty
?
Reference: String.Empty vs ""
It just doesn't matter!
Some past discussion of this:
http://www.codinghorror.com/blog/archives/000185.html
http://blogs.msdn.com/brada/archive/2003/04/22/49997.aspx
http://blogs.msdn.com/brada/archive/2003/04/27/50014.aspx
When you're visually scanning through code, "" appears colorized the way strings are colorized. string.Empty looks like a regular class-member-access. During a quick look, its easier to spot "" or intuit the meaning.
Spot the strings (stack overflow colorization isn't exactly helping, but in VS this is more obvious):
var i = 30;
var f = Math.Pi;
var s = "";
var d = 22.2m;
var t = "I am some text";
var e = string.Empty;
string mystring = "";
ldstr ""
ldstr
pushes a new object reference to a string literal stored in the metadata.
string mystring = String.Empty;
ldsfld string [mscorlib]System.String::Empty
ldsfld
pushes the value of a static field onto the evaluation stack
I tend to use String.Empty
instead of ""
because IMHO it's clearer and less VB-ish.