Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
communitycreator

How to check if a string value is empty or null in C#

Theodore Kelechukwu Onyejiaku

Overview

A string value is said to be null or empty when the value has nothing. We can use the IsNullOrEmpty() method to check if a string is valueless. This method checks if a string is null or an empty string.

Syntax

public static bool IsNullOrEmpty(String str)

Parameters

  • str: The string to check if it is empty or not.

Return value

IsNullOrEmpty() returns True if the string is empty; otherwise, it returns False.

Example

In the code below, we demonstrate the use of the IsNullOrEmpty() method.

// create our class
class EmptyOrNullString
{
    // main method
    static void Main()
    {
      // create our strings
      string str1 = "Edpresso!";
      string str2 = "";

      // check if strings are empty
      // or null
      bool str3 = string.IsNullOrEmpty(str1);
      bool str4 = string.IsNullOrEmpty(str2);

      // log out the returned values
      System.Console.WriteLine(str3);
      System.Console.WriteLine(str4);
    }
}
Example of the IsNullOrEmpty method

Explanation

  • The method returns True for str2 because it is empty.
  • The method returns False for str1 because it is not empty.

RELATED TAGS

c#
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring