Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a const array

Is it possible to write something similar to the following?

public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" }; 
like image 447
Jaime Oro Avatar asked Feb 28 '11 13:02

Jaime Oro


People also ask

How do you declare a constant array in C++?

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};

How do I declare a const array in TypeScript?

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[] ).

What is the correct way to declare a constant array in JavaScript?

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.

Can you modify a const array C++?

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.


1 Answers

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 }; 
like image 102
Cody Gray Avatar answered Oct 25 '22 07:10

Cody Gray