Is it possible to write something similar to the following?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
In C++, the most common way to define a constant array should certainly be to, erm, define a constant array: const int my_array[] = {5, 6, 7, 8};
Use a const assertion to declare a const array in TypeScript, e.g. const arr = [10, 5] as const . Const assertions enable us to set the elements of an array to readonly , indicating to the language that the type in the expression will not be widened (e.g. from [1, 2] to number[] ).
To create a const array in JavaScript we need to write const before the array name. The individual array elements can be reassigned but not the whole array.
You can't. The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable.
Yes, but you need to declare it readonly
instead of const
:
public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
The reason is that const
can only be applied to a field whose value is known at compile-time. The array initializer you've shown is not a constant expression in C#, so it produces a compiler error.
Declaring it readonly
solves that problem because the value is not initialized until run-time (although it's guaranteed to have initialized before the first time that the array is used).
Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:
public enum Titles { German, Spanish, Corrects, Wrongs };
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