Why would you declare an IEnumerable<T>
readonly
?
From the this article on async & await we have the following code.
class OrderHandler
{
private readonly IEnumerable<Order> _orders;
public OrderHandler()
{
// Set orders.
}
public IEnumerable<Order> GetAllOrders()
{
return _orders;
}
}
IEnumerable<T>
is immutable. How is this different from the readonly
keyword?
The readonly
keyword here applies to the field _orders
. It simply means that the field can not be assigned a different value during the lifetime of the object. For example, this is not possible:
class OrderHandler
{
private readonly IEnumerable<Order> _orders;
public OrderHandler()
{
// Set orders.
}
void SomeMethod()
{
_orders = new Order[0];
}
}
You will receive this compiler error:
A
readonly
field cannot be assigned to (except in a constructor or a variable initializer)
This does not make the collection read-only. For example, you could still do this:
class OrderHandler
{
public readonly IEnumerable<Order> Orders;
public OrderHandler()
{
Orders = new List<Order>();
}
}
((List<Order>)OrderHandler.Orders).Add(new Order());
Which would probably violate the thread-safety of the class. See Tigran's answer for information on immutable collections.
Further Reading