Empty String in C#

In this article we will discuss about the empty string in c#.
  • 4482

An empty string is a valid instance of a System.String object that contains zero characters.There are two ways to create an empty string.  We can either use the string. Empty property or we can simply assign a text value with no text in it. 

The following code snippet creates two empty strings.

string empStr= string.Empty;
string empStr2 = "";

Both of the statements above generate the same output.

Console.WriteLine("Start" + empStr + "End");
Console.WriteLine
("Start"+ empStr2 + "End");

 An empty string is sometimes used to compare the value of other strings. The following code snippet uses an empty string to compare with the name string.

string name = "Mahesh Chand";
if (name != empStr)
{
    Console.WriteLine(name);
}

In real world coding,we will probably never create an empty string unless you plan to use it somewhere else as a non-empty string. We can simply use the string. Empty direct to compare a string with an empty string.

if (name != string.Empty)
{
    Console.WriteLine(name);
}

Here is a complete example of using an empty string.

string empStr = string.Empty;
string empStr2 = "";
string name = "Mahesh Chand";
if (name != empStr)
{
   Console.WriteLine(name);
}
if (name != string.Empty)
{
    Console.WriteLine(name);
}


Further Readings
 
You may also want to read these related articles.
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.