5

In C++, if I want an object to be initialized at compile time and never change thereafter, I simply add the prefix const.

In C#, I write

    // file extensions of interest
    private const List<string> _ExtensionsOfInterest = new List<string>()
    {
        ".doc", ".docx", ".pdf", ".png", ".jpg"
    };

and get the error

A const field of a reference type other than string can only be initialized with null

Then I research the error on Stack Overflow and the proposed "solution" is to use ReadOnlyCollection<T>. A const field of a reference type other than string can only be initialized with null Error

But that doesn't really give me the behavior I want, because

    // file extensions of interest
    private static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>()
    {
        ".doc", ".docx", ".pdf", ".png", ".jpg"
    };

can still be reassigned.

So how do I do what I'm trying to do?

(It's amazing how C# has every language feature imgaginable, except the ones I want)

2
  • 7
    private static readonly ReadOnlyCollection<string>
    – D Stanley
    Commented Apr 12, 2016 at 15:12
  • You found the answer and miss important point of it (it contains the hint). Learning is hard.
    – Sinatr
    Commented Apr 12, 2016 at 15:17

1 Answer 1

12

You want to use the readonly modifier

private readonly static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>()
{
    ".doc", ".docx", ".pdf", ".png", ".jpg"
};

EDIT

Just noticed that the ReadOnlyCollection type doesnt allow an empty constructor or supplying of the list in the brackets. You must supply the list in the constructor.

So really you can just write it as a normal list which is readonly.

private readonly static List<string> _ExtensionsOfInterestList = new List<string>()
{
    ".doc", ".docx", ".pdf", ".png", ".jpg"
};

or if you really want to use the ReadOnlyCollection you need to supply the above normal list in the constructor.

private readonly static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>(_ExtensionsOfInterestList);

Not the answer you're looking for? Browse other questions tagged or ask your own question.