How to Declare Empty String Array? C# syntax

There are three simple ways to declare an Empty String Array:

using System;
namespace EmptyArrayApplication
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Variant 1
            string[] myEmptyArray1 = new string[] { };
            //Variant 2
            string[] myEmptyArray2 = { };
            //Variant 3
            string[] myEmptyArray3 = Array.Empty<string>();//for .NET Framework 4.6 and later
            Console.WriteLine(myEmptyArray1.Length);
            Console.WriteLine(myEmptyArray2.Length);
            Console.WriteLine(myEmptyArray3.Length);
        }
    }
}

If you use .net Framework 4.6 or later use Array.Empty() construction. Usually, an empty array uses to return the default value from the method.

Leave a Reply

Your email address will not be published.