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)
Yes. const is there in C, from C89.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
The const (read: constant) keyword in C# is used to define a constant variable, i.e., a variable whose value will not change during the lifetime of the program. Hence it is imperative that you assign a value to a constant variable at the time of its declaration.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With