none
What is the difference between 1) null 2)empty and 3)"" in C#

    Question

  • What these mean?

    string s= null;

    string s=String.Empty;

    string s=""

    Thanks,

    .Net


    .NETVinodh

    Thursday, August 02, 2012 2:30 PM

Answers

  • This is, in fact, more complicated than what is suggested here due to string interning.  

    First off - the comments about null are all accurate - it's more a matter of the difference between "" and String.Empty.

    String.Empty and "" actually do become the same string in memory, since the runtime interns the constant value of "", and both String.Empty and "" end up pointing to the same interned value.  In fact, it's impossible (I believe) to make a string that is the empty string which isn't the same reference as "", as all of the string manipulation methods, as well as StringBuilder, will return String.Empty if the resulting value has zero length.

    As such, String.Empty will always be exactly the same as "".

    You can see this, btw, by making a small test:

    using System;
    using System.Text;
    
    internal class Program
    {
        private static void Main()
        {
            // These are identical, ie: they have true reference equality 
            Console.WriteLine(Object.ReferenceEquals(string.Empty, ""));
    
            // Build an empty string from code in a way that you know it's generated at runtime
            string empty = new string('a', 1).Trim('a');
    
            // These still are the same reference
            Console.WriteLine(Object.ReferenceEquals(string.Empty, empty));
    
            // As is:
            StringBuilder builder = new StringBuilder();
            Console.WriteLine(Object.ReferenceEquals("", builder.ToString()));
    
            // Force this to intern
            string interned = string.Intern("");
            Console.WriteLine(Object.ReferenceEquals("", interned));
    
            Console.WriteLine("Press key to exit:");
            Console.ReadKey();
        }
    }


    You'll see that, pretty much no matter what you do, an empty string will always refer to the same instance in memory - the interned "" value which gets initialized first in String.Empty.

    (Note that this is fairly unique to empty strings, however.... Other string constant values use interning, but methods won't create the interned value.)

    Sebastian - You mentioned "while String.Empty is a language constant."  Just FYI - this isn't a language constant, but actually part of the framework.  String.Empty is a static member of the string class, so not technically a language related function, but a member of a framework type.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Thursday, August 02, 2012 10:43 PM
    Moderator
  • Hi

    String.Empty and "" are almost the same, both refer to an existing string that has no content.

    Said almost because, "" creates a temporary string in memory (to have something to compare against) while String.Empty is a language constant.

    On the other hand, null means nothing, no object at all.

    In more familiar terms, String.Empty is like having an empty drawer while null means no drawer at all!


    Sebastian Sajaroff Senior DBA Pharmacies Jean Coutu

    • Marked as answer by .NETVinodh Thursday, August 02, 2012 2:52 PM
    Thursday, August 02, 2012 2:42 PM

All replies

  • string s = null;

    No object exists, but the variable s that references a string object does exist, but it references nothing.

    string s = String.Empty;
    string s = "";

    Are equivalent.  Both the object and the variable exist.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    • Proposed as answer by Heslacher Thursday, August 02, 2012 2:42 PM
    Thursday, August 02, 2012 2:41 PM
  • Hi,

    =null means the string isn`t initialized and has no value

    String.Empty and ="" are the same whereas String.Empty is just a static readonly representing ""


    Hannes

    If you have got questions about this, just ask.

    In a perfect world,
    users would never enter data in the wrong form,
    files they choose to open would always exist
    and code would never have bugs.

    C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/

    Thursday, August 02, 2012 2:41 PM
  • Hi

    String.Empty and "" are almost the same, both refer to an existing string that has no content.

    Said almost because, "" creates a temporary string in memory (to have something to compare against) while String.Empty is a language constant.

    On the other hand, null means nothing, no object at all.

    In more familiar terms, String.Empty is like having an empty drawer while null means no drawer at all!


    Sebastian Sajaroff Senior DBA Pharmacies Jean Coutu

    • Marked as answer by .NETVinodh Thursday, August 02, 2012 2:52 PM
    Thursday, August 02, 2012 2:42 PM
  • null = no memory allocated to the string variable. no valid object of string.

    String.Empty = object of String class(all properties of String class will be available to it, but its value is empty)

    "" = a blank string. memory allocated to the variable.

    regards

    joon

    Thursday, August 02, 2012 2:44 PM
  • I wrote a blog post about this here.
    http://www.danderson.me/practices/empty-pattern/

    I think what has been left out is more important, and that's why do these exist and what does Empty really mean? SomeType.Empty is actually a public static readonly field, and a pattern and practice for an easily accessible way to get the default value for a type that's instantiated. For instance, what's the default value of a value type? It's not null because value types are not nullable, so that leaves a newly instantiated struct. What happens when you instantiate a value type? It's backing fields are instantiated to their default values (eg. int = 0, bool = false, string = null, uint = 0, et cetera).

    For a value type, the following is true:

    • ValueType.Empty should be the same as saying default(ValueType)
    • The default value for an instantiated value type should be ValueType.Empty, which should be considered an unmodified, instantiated value type

    For a reference type, the following is true:

    • The default value for a reference type is null
    • default(ReferenceType) is null, because that is the default value for a reference type
    • The default value for an instantiated reference type should be ReferenceType.Empty, which should be considered an unmodified, instantiated reference type

    Use the Empty pattern when:

    • Value semantics makes sense

    Currently developing FaultTrack. I occassionally blog about C# and .NET.
    Hoping to become a MVP by 2013. Email: danderson [at] dcomproductions [dot] com

    Thursday, August 02, 2012 5:29 PM
  • On 32bit CPU and Unicode String.

    1) string mystring = null;

    This means you have a 32bits address called mystring.

    2) string mystring = string.Emtpy;

    This means you have a 32bits address called mystring and it points to existing "" somewhere else.

    3) string mystring = "";

    This means you have 32bits address called mystring and an additional (20*8)bits value called "" locally.

    Please let me know if I am wrong. Seems like JIT should just replace "" with string.Empty to save memory. Unless having local "" has performance benefit? But obviously the GC will be horrible. I am trying to learn as well. I used to use "" because it was so easy.

    Also from the book, String is a readonly reference type. You simply cannot modify its referenced value because it is readonly.

    ====

    I read other source, some actually say "" doesn't create extra copy because .NET will resolve duplicate itself. They also say "" is a constant at compile time, which is faster, from dotnetperl. So, essentially "" is better? Also use (x.Length == 0) instead of (x == ""), although I thought JIT should convert this for us.

    =====

    Looks like "" is better because it is a constant at compile time and it is interned to save memory. And use string.IsNullOrEmpty(myStr) or  (myStr.Length == 0) based on your desire. The IsNullOrEmpty() is recommended since it does null check.

    Thursday, August 02, 2012 6:11 PM
  • This is, in fact, more complicated than what is suggested here due to string interning.  

    First off - the comments about null are all accurate - it's more a matter of the difference between "" and String.Empty.

    String.Empty and "" actually do become the same string in memory, since the runtime interns the constant value of "", and both String.Empty and "" end up pointing to the same interned value.  In fact, it's impossible (I believe) to make a string that is the empty string which isn't the same reference as "", as all of the string manipulation methods, as well as StringBuilder, will return String.Empty if the resulting value has zero length.

    As such, String.Empty will always be exactly the same as "".

    You can see this, btw, by making a small test:

    using System;
    using System.Text;
    
    internal class Program
    {
        private static void Main()
        {
            // These are identical, ie: they have true reference equality 
            Console.WriteLine(Object.ReferenceEquals(string.Empty, ""));
    
            // Build an empty string from code in a way that you know it's generated at runtime
            string empty = new string('a', 1).Trim('a');
    
            // These still are the same reference
            Console.WriteLine(Object.ReferenceEquals(string.Empty, empty));
    
            // As is:
            StringBuilder builder = new StringBuilder();
            Console.WriteLine(Object.ReferenceEquals("", builder.ToString()));
    
            // Force this to intern
            string interned = string.Intern("");
            Console.WriteLine(Object.ReferenceEquals("", interned));
    
            Console.WriteLine("Press key to exit:");
            Console.ReadKey();
        }
    }


    You'll see that, pretty much no matter what you do, an empty string will always refer to the same instance in memory - the interned "" value which gets initialized first in String.Empty.

    (Note that this is fairly unique to empty strings, however.... Other string constant values use interning, but methods won't create the interned value.)

    Sebastian - You mentioned "while String.Empty is a language constant."  Just FYI - this isn't a language constant, but actually part of the framework.  String.Empty is a static member of the string class, so not technically a language related function, but a member of a framework type.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Thursday, August 02, 2012 10:43 PM
    Moderator