C# - How to declare or return an empty array

I find this syntax to be the most readable (using an implicitly sized array [] with an empty collection initializer { }).

var empty = new int[] { };

Alternatively:

using System;
 
namespace Zuga.net
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Use the Collection initializer
            var empty1a = new int[] { };
            int[] empty1b = { };
 
            // 2. Specify a zero length
            var empty2 = new int[0];
 
            // 3. New in .NET 4.6
            var empty3 = Array.Empty<int>();
        }
    }
}

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath