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.
-
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. -
class Program { ... }
- This is a class definition. The name of the class isProgram
. -
static void Main(string[] args){ ... }
- This is the Main method, which is the entry point for the program. The program begins executing here. -
int[] myArray = new int[0];
- We declare an array namedmyArray
of integers using ‘int[]‘. The ‘new int[0]’ means we are initializing it with zero elements, therefore it’s currently an empty array. -
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. -
Console.WriteLine("Array is empty.");
andConsole.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#.