Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to create an empty string array
Creating an empty string array in C# is useful when you need to declare an array without initial elements. There are several ways to create an empty string array, each serving different purposes depending on your requirements.
Syntax
Following are the different ways to create an empty string array −
string[] str = new string[] {};
string[] str = new string[0];
string[] str = {};
Using Array Initializer Syntax
The most straightforward way to create an empty string array is using the array initializer syntax with empty braces −
using System;
public class Demo {
public static void Main() {
string[] str = new string[] {};
Console.WriteLine("Array Length: " + str.Length);
Console.WriteLine("String Array elements won't get displayed since it's empty...");
for (int i = 0; i
The output of the above code is −
Array Length: 0
String Array elements won't get displayed since it's empty...
Using Fixed-Size Constructor
You can create an empty array by specifying zero as the size −
using System;
public class Demo {
public static void Main() {
string[] str = new string[0];
Console.WriteLine("Array created with size 0");
Console.WriteLine("Array Length: " + str.Length);
Console.WriteLine("Is array empty? " + (str.Length == 0));
}
}
The output of the above code is −
Array created with size 0
Array Length: 0
Is array empty? True
Using Simplified Syntax
C# allows a simplified syntax without the explicit type declaration −
using System;
public class Demo {
public static void Main() {
string[] str = {};
Console.WriteLine("Empty array created with simplified syntax");
Console.WriteLine("Array Length: " + str.Length);
// Adding elements later using Array.Resize
Array.Resize(ref str, 2);
str[0] = "Hello";
str[1] = "World";
Console.WriteLine("After resizing and adding elements:");
foreach (string s in str) {
Console.WriteLine(s);
}
}
}
The output of the above code is −
Empty array created with simplified syntax
Array Length: 0
After resizing and adding elements:
Hello
World
Comparison of Methods
| Method | Syntax | Use Case |
|---|---|---|
| Array Initializer | new string[] {} | Most explicit and readable |
| Fixed-Size Constructor | new string[0] | When size is calculated dynamically |
| Simplified Syntax | {} | Concise code when type is inferred |
Conclusion
Empty string arrays in C# can be created using multiple approaches, with new string[] {} being the most explicit method. These empty arrays have zero length and can be resized later using methods like Array.Resize() when needed.
