A .NET Framework v4.5+ solution that improves on tdbeckett's answer:
using System.Collections.ObjectModel;
// ...
public ReadOnlyCollection<string> Titles { get; } = new ReadOnlyCollection<string>(
new string[] { "German", "Spanish", "Corrects", "Wrongs" }
);
Note: Given that the collection is conceptually constant, it may make sense to make it static
to declare it at the class level.
The above:
Initializes the property's implicit backing field once with the array.
Note that { get; }
- i.e., declaring only a property getter - is what makes the property itself implicitly read-only (trying to combine readonly
with { get; }
is actually a syntax error).
Alternatively, you could just omit the { get; }
and add readonly
to create a field instead of a property, as in the question, but exposing public data members as properties rather than fields is a good habit to form.
Creates an array-like structure (allowing indexed access) that is truly and robustly read-only (conceptually constant, once created), both with respect to:
IReadOnlyList<T>
solution, where a (string[])
cast can be used to gain write access to the elements, as shown in mjepsen's helpful answer.IReadOnlyCollection<T>
interface, which, despite the similarity in name to class ReadOnlyCollection
, does not even support indexed access, making it fundamentally unsuitable for providing array-like access.)