Check if string contains some value or empty or null in C# quick tip | Blowork

Check if string contains some value or empty or null in C# quick tip

Hello all,

We need to work on string operations quite often in projects. Many times we need to check if string is empty or null. Now there is difference in null and empty value.

In C# -

  • A string will be null if it has not been assigned a value.
  • A string will be empty if it is assigned "" or String.Empty

Here is example:

/*

Goal: I need to check if string has some value (Not empty) Or NULL.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IsNullOrEmptyDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string emptyString = "";
            string nullString = null;

            if (string.IsNullOrEmpty(emptyString))
            {
                Console.WriteLine("emptyString - String is either null or does not contain any data.");
            }

            if (string.IsNullOrEmpty(nullString))
            {
                Console.WriteLine("nullString - String is either null or does not contain any data.");
            }

            Console.ReadKey();
        }
    }
}