'new object[] {} vs Array.Empty<object>()

When I type the following code:

object[] objects = new object[] { };

Visual Studio tells me:

Avoid unnecessary zero-length allocations. Use Array.Empty<object>() instead.

Are there any actual implications of using one over the other?

What is the reason for the warning?



Solution 1:[1]

Using Array.Empty is useful to avoid unnecessary memory allocation. Refer the code from .NET Library itself below:

[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static T[] Empty<T>()
{
    Contract.Ensures(Contract.Result<T[]>() != null);
    Contract.Ensures(Contract.Result<T[]>().Length == 0);
    Contract.EndContractBlock();

    return EmptyArray<T>.Value;
}
...
// Useful in number of places that return an empty byte array to avoid unnecessary memory allocation.
internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

Source: https://referencesource.microsoft.com/#mscorlib/system/array.cs,bc9fd1be0e4f4e70

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 adityap