What is the difference between String.Empty and “” (empty string)?

后端 未结 17 1559
礼貌的吻别
礼貌的吻别 2020-11-22 03:25

In .NET, what is the difference between String.Empty and \"\", and are they interchangable, or is there some underlying reference or Localization i

相关标签:
17条回答
  • 2020-11-22 04:23

    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.

    0 讨论(0)
  • 2020-11-22 04:24

    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 in String.Empty?

    Reference: String.Empty vs ""

    0 讨论(0)
  • 2020-11-22 04:25

    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

    0 讨论(0)
  • 2020-11-22 04:26

    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;
    
    0 讨论(0)
  • 2020-11-22 04:27
    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.

    0 讨论(0)
提交回复
热议问题