Search code examples
c#arraysenumerable

Explicit cast required for Enumerable.Empty<T>


Every example I've read so far (google result/stack question) that expalins the use of "Enumerable.Empty" says that i should be able to use it with an array. The VS compiler however, won't allow me to use it unless i explicitly cast it to the array despite defining the type.

Why is this? (I've seen no reference of the cast being required in the ~20 related stack questions or general google results I've looked at)

//The internet says this should work, but i get a "Cannot implicitly convert type" error
public byte[] dataA = Enumerable.Empty<byte>();
public string[] dataB = Enumerable.Empty<string>(); 

//Throws no error, but the cast's requirement is never mentioned
public byte[] dataA = (byte[])Enumerable.Empty<byte>();
public string[] dataB = (string[])Enumerable.Empty<string>();

Solution

  • You meant Array.Empty<T>, not Enumerable:

    public byte[] dataA = Array.Empty<byte>();
    public string[] dataB = Array.Empty<string>();