Declare and initialize an empty array in C#
This post will discuss how to declare and initialize an empty array in C#.
There are several ways to declare and initialize an empty array in C#. Some of them are demonstrated below:
1. T[] array = new T[] {}
|
1 2 3 4 5 6 7 8 9 10 |
using System; public class Example { public static void Main() { int[] array = new int[] {}; Console.WriteLine(array.Length); } } |
2. T[] array = new T[0]
|
1 2 3 4 5 6 7 8 9 10 |
using System; public class Example { public static void Main() { int[] array = new int[0]; Console.WriteLine(array.Length); } } |
3. T[] array = {}
|
1 2 3 4 5 6 7 8 9 10 |
using System; public class Example { public static void Main() { int[] array = {}; Console.WriteLine(array.Length); } } |
4. T[] array = Array.Empty<T>()
|
1 2 3 4 5 6 7 8 9 10 |
using System; public class Example { public static void Main() { int[] array = Array.Empty<int>(); Console.WriteLine(array.Length); } } |
5. T[] array = Enumerable.Empty<T>().ToArray()
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = Enumerable.Empty<int>().ToArray(); Console.WriteLine(array.Length); } } |
6. T[] array = Enumerable.Repeat(0, 0).ToArray()
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = Enumerable.Repeat(0, 0).ToArray(); Console.WriteLine(array.Length); } } |
That’s all about declaring an empty array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)