Null and string in C #. The difference between empty and equal space

Source: Internet
Author: User

Let's look at an effect chart first.

When you define only one str instead of allocating memory for it, use string str=null, but you must assign a value to it before you use it, such as str= "XXXX", which is initialized for it.
and string str= string. Empty is defined and initialized together it is actually equivalent to string str=null;str= "";
When used specifically, if you decide to assign a value to str before using string str=null, otherwise use string str= string. Empty, otherwise a null pointer exception may be thrown when the program is running


String. Empty does not allocate storage space
"" Allocates a storage space with an empty length
So you usually use string. Empty

In order to cross the platform later, or with String.Empty

In C #, most of the cases "" and string. Empty can be used interchangeably. Like what:

The code is as follows Copy Code

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

if (s = = string. Empty) {
//
}

If statement set up


Several ways to determine an empty string are in the order of performance from highest to lowest:

The code is as follows Copy Code

S.length = 0 is superior to s = = string. Empty is superior to S = = ""

Your question about String.Empty and Null is this, both of which represent an empty string, with one focus on the difference between string str1= String.Empty and string str2=null, so that after the definition, str1 is an empty string, The empty string is a special string, except that the value of this string is null, and in memory there is an accurate point, string str2=null, so defined, just defines a reference to a string class, STR2 does not point to anywhere, if not instantiated before use, will have an error. The TextBox1.Text value is a zero-length string "".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.