let's say I need an empty array of a Book
class in C#.
public class Book
{
public string Title { get; set; }
public Author Author { get; set; }
}
I found the following 3 options to achieve this:
new Book[0]
Array.Empty<Book>()
ArraySegment<Book>.Empty
Can you suggest which one I should go for and the difference between them, please?
In most cases you would use Array.Empty<Book>()
. Note that this will return the same instance each time it is called.
new Book[0]
will produce a new array. This will require a new object to be allocated, but could be used if you want your array to compare differently to other empty arrays.
ArraySegment<Book>.Empty
does not produce an array, but an ArraySegment
. ArraySegment is typically used to represent a smaller section of an array. If you should use an ArraySegment or an Array is a more complicated question, especially since there are a wide variety of other collection types to chose between.