OneBite.Dev - Coding blog in a bite size

Check If Array Is Empty In C#

Code snippet for how to Check If Array Is Empty In C# with sample and detail explanation

Checking if an array is empty in C# can be an important part of programming to ensure your code functions efficiently and correctly. This article will provide you with a simple and understanding tutorial on how to go about it.

Code snippet: Checking if an Array is Empty

using System;

class Program {
    static void Main(string[] args) {
        int[] myArray = new int[0];

        if (myArray.Length == 0) {
            Console.WriteLine("Array is empty.");
        } else {
            Console.WriteLine("Array is not empty.");
        }
    }
}

Code Explanation: Checking if an Array is Empty

Let’s break down this code step by step.

  1. using System; - This is a directive to use the System namespace, which provides functions for dealing with local time and UTC time, as well as basic data processing functionalities.

  2. class Program { ... } - This is a class definition. The name of the class is Program.

  3. static void Main(string[] args){ ... } - This is the Main method, which is the entry point for the program. The program begins executing here.

  4. int[] myArray = new int[0]; - We declare an array named myArray of integers using ‘int[]‘. The ‘new int[0]’ means we are initializing it with zero elements, therefore it’s currently an empty array.

  5. if(myArray.Length == 0){ ... } else { ... } - An if-else conditional statement in which we use myArray.Length to get the total number of elements in the array. If the Length property equals 0, it means the array is empty.

  6. Console.WriteLine("Array is empty."); and Console.WriteLine("Array is not empty."); - If the array is empty, the program will print “Array is empty.” If not, it will print “Array is not empty.”

The code finally checks if the array is empty and gives appropriate output, returning “Array is empty.” as we initialized it to be empty. This code can be used whenever you need to check if an array is empty in C#.

c-sharp