Difference between Null and Empty in String Variables

Whether Strings Are Empty 

We may have a confusion when we want to understand whether String type variables are empty or filled. Let's explain the possibilities here.

string a;

Currently, variable a is defined but no assignment has been made. That's why variable a is  null.

a=""; 

Here it is stated that variable a will be empty. But variable a is no longer null. Because an assignment has been made, even if it is empty. The variable a is  empty .

We can check if a string variable is empty in two ways. 

The if ( a =="") or if ( a == string.empty ) statements mean the same thing and let us know if the variable is empty.

a=""; 

Here, the variable a is not empty, it is filled because one space character is assigned. Spaces are also characters.

Check out the example below.

Note: You can also examine the IsNullOrEmpty function which you can find in next pages of our site.

using string.empty, if string null, find out if string is empty, is string empty or null, whether string is empty

EXERCISES

Difference between null and empty in string variables

string[] numbers = new string[5];

numbers[0] = "534";
numbers[2] = "115";
numbers[3] = "";
A 5-element sequence of numbers has been defined above, and then some of its elements have been assigned a value. Elements 0 and 2 were assigned a value, element 3 was determined as empty , elements 1 and 4 were left as null , that is, no assignment was made.
Let's try different methods to put "-" for empty elements while printing all the elements of the array into the label:
foreach (string in numbers)
{
if ( i == null ) label1.Text += "-\n";
else label1.Text += i + "\n";
}
The above loop only allows "-" to be set for null elements. In other words, "-" will be put for elements 1 and 4.
foreach (string in numbers)
{
if ( i=="" ) label1.Text += "-\n";
else label1.Text += i + "\n";
}

The above loop only allows "-" to be set for elements that are empty. In other words, "-" will be put for element 3.

foreach (string in numbers)
{
if (i == null || i=="") label1.Text += "-\n";
else label1.Text += i + "\n";
}

Here, "-" will be set for null or empty elements, that is, "-" will be put for elements 1, 3 and 4.



COMMENTS




Read 938 times.

Online Users: 281



difference-between-null-and-empty-string