user12669123
user12669123

Reputation:

IF statement checking for null or String.Empty

So I have a list with some data in it such as an input path, output path as well as column headings. As can been seen there are six column headings however some may be null as they do not have to be used. Because of this I created a method to filter the data so that only useful data remains.

List<string> data = new List<string> { "C:/", "C:/Documents", "Hello", Goodbye". null, null, null, null } // Data to be passed into method
List<string> filteredData = new List<string>();

public void FilterData(List<string> data)
{
   foreach (var d in data)
   {
      if (d != null || d != String.Empty)
      {
         filteredData.Add(d);
      }
   }
}

Why is it that when I pass the List data into this method none of the data is filtered so that filteredData will contains the same as data, but when I use the following (if statement only evaluates if not null) it filters correctly?

public void FilterData(List<string> data)
    {
       foreach (var d in data)
       {
          if (d != null)
          {
             filteredData.Add(d);
          }
       }
    }

Thanks

Upvotes: 0

Views: 1672

Answers (2)

jason.kaisersmith
jason.kaisersmith

Reputation: 9610

The problem is that you are using a logical OR when you should be using a logical AND.

You only want to add it when it is not null AND not empty.

BTW: There is an easier way:

foreach (var d in data)
{
      if (!String.IsNullOrEmpty(d))
      {
          ....

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

You:

if (d != null || d != String.Empty)

This is always true as d cannot be both null and ""; it has to be different from at least one of them.

Some correct alternatives:

if (d != null && d != "")
if (!(d == null || d == ""))
if (!string.IsNullOrEmpty(d))

Upvotes: 1

Related Questions