Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the equivalent of C++'s "const" in C#? [duplicate]

Tags:

c#

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)

like image 312
user6048670 Avatar asked Apr 12 '16 15:04

user6048670


People also ask

Is there const in C?

Yes. const is there in C, from C89.

How does the const keyword work in C?

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.

What is const keyword in C#?

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.


1 Answers

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);
like image 79
CathalMF Avatar answered Sep 27 '22 16:09

CathalMF