|
-
Aug 3rd, 2007, 04:21 AM
#1
Thread Starter
Hyperactive Member
[2.0] Instantiating a string
Whats best practice?
string test = null;
string test = "";
string test = string.Empty;
Thanks!
-
Aug 3rd, 2007, 04:28 AM
#2
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|