Loading ...

Null vs Empty

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  getting started / general asp.net   » Null vs Empty

Null vs Empty

Posts under the topic: Null vs Empty

Posted: 9/7/2010

Contributor 2237  points  Contributor
  • Joined on: 9/24/2009
  • Posts: 172

Hello Experts,

Please take a look -

1. string str = null;

AND

2. string str = "";(Empty)

Now can anyone tell me which str string will take higher size and what is difference between null and empty?

 

Thanx in advance.

 


Posted: 9/7/2010

Guru 16813  points  Guru
  • Joined on: 4/19/2009
  • Posts: 490
  Answered

From MSDN:

 

Null Strings and Empty Strings

An empty string is an instance of a System.String object that contains zero characters. Empty strings are used quite commonly in various programming scenarios to represent a blank text field. You can call methods on empty strings because they are validSystem.String objects. Empty strings are initialized like this:

string s = "";

By contrast, a null string does not refer to an instance of a System.String object and any attempt to call a method on a null string results in a NullReferenceException. However, you can use null strings in concatenation and comparison operations with other strings. The following examples illustrate some cases in which a reference to a null string does and does not cause an exception to be thrown:

string str = "hello";
string nullStr = null;
string emptyStr = "";

string tempStr  = str + nullStr; // tempStr = "hello"
bool b = (emptyStr == nullStr);// b = false;
emptyStr + nullStr = ""; // creates a new empty string
int I  = nullStr.Length; // throws NullReferenceException

 


Posted: 9/8/2010

Professional 8338  points  Professional
  • Joined on: 4/15/2009
  • Posts: 424
  Answered
Page 1 of 1 (3 items)