-2

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>();
Pac0
  • 21,465
  • 8
  • 65
  • 74
Reahreic
  • 596
  • 2
  • 7
  • 26

3 Answers3

4

Enumerable.Empty generates an empty sequence, not an array.

If you want to convert the sequence to an array then you can call ToArray:

byte[] dataA = Enumerable.Empty<byte>().ToArray();
string[] dataB = Enumerable.Empty<string>().ToArray(); 

If you really want an empty array then why not say:

byte[] dataA = new byte[0];
string[] dataB = new string[0];

Your casting might work, but this is very much relying on how Empty is implemented. It may just return an empty array, or it may return something else that implements IEnumerable but is empty.

Sean
  • 60,939
  • 11
  • 97
  • 136
3

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

public byte[] dataA = Array.Empty<byte>();
public string[] dataB = Array.Empty<string>(); 
Rup
  • 33,765
  • 9
  • 83
  • 112
2
  1. You can use the ToArray() Linq method to get an Array<T> out of your IEnumerable<T>. So, as already said, you could create an empty sequence using Enumerable.Empty<T> and then convert it to an array.

  2. Note that in general the static Array<T>.Empty is recommended way to create an empty array, if you explicitly need one.

  3. Avoid those casts (byte[]) if you can, they will probably bite you hard in the future. Indeed it is not required at all.

Pac0
  • 21,465
  • 8
  • 65
  • 74