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)

Community
  • 1
  • 1
user6048670
  • 2,861
  • 4
  • 16
  • 20

1 Answers1

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);
CathalMF
  • 9,705
  • 6
  • 70
  • 106