Results 1 to 2 of 2

Thread: [2.0] Instantiating a string

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Mar 2006
    Location
    Madrid
    Posts
    325

    [2.0] Instantiating a string

    Whats best practice?

    string test = null;
    string test = "";
    string test = string.Empty;

    Thanks!

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] Instantiating a string

    The first one is different to the other two. String is a class, so strings ae reference type objects. That means that setting a string variable to null is actually setting the variable to refer to no object at all. The other two set the variable to refer to a string on the heap that contains no characters. Note that in some situations a null reference of type string is treated in the same way as an empty string, which is by design for the sake of convenience. They are not the same thing though, and in other circumstances using a null reference where an empty string is expected will cause an excption to be thrown.

    To answer your question, the third option is considered to be best practice, although .NET is optimised in such a way that if you use one or more empty string literals in your code they are all converted to use the same string object as the String.Empty property refers to anyway.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width