How to declare a constant array in C#? Problem with const and possible solutions
Hello everyone! I'm a beginner C# developer, and I encountered a problem when trying to declare a constant array. I want to create a string array that should never change during program execution. I'm trying to do this:
```csharp
public const string[] DaysOfWeek = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
```
But the compiler gives an error: "The expression being assigned to 'DaysOfWeek' must be constant". I understand that `const` only works for simple types (int, double, string), but not for reference types like arrays. However, I need exactly constant behavior — the array should be immutable and initialized once.
I've seen that you can use `readonly`, but it's not exactly the same as `const`. With `readonly`, the array can be created in the constructor
No answers yet.
Log in to leave an answer