Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] hhrmm, const array in C# ?

Started by UnshavenBastard Oct 18, 2004 at 4:23 AM 7 replies 21.9k views
Original Post
UnshavenBastard
UnshavenBastard
I want to have an array of const strings, but the compile complains "only variable arrays can be initialized" or something like that. private static string[] strings = { "hello", "there", "whatever" } works, but I don't want just static, I really want: private const string[] strings = { "hello", "there", "whatever" } So, why doesn't the damn compiler like that? I think it makes much sense to have an array of const (iaw. non-modifiable) strings.
aidan_walsh
aidan_walsh
You're not defining an array of constant Strings, you're defining a constant array of Strings.
www.aidanwalsh(.net)(.info)
UnshavenBastard
UnshavenBastard
yeah, I figured, but I don't really neither 'cause the compiler won't let me do this.
and it doesn't work to put the "const" in either place, I should have questioned more general like "is it possible at all to make an array of const items in C#", I guess.

Dean Harding
Dean Harding
C# has the readonly modifier, so you can use the following:

private static readonly string[] strings ={  "hello", "there", "whatever"};


It works similar to const, except a readonly field can be initialized in the constructor (whereas a const must be initialized where it is declared).
RenZimE
RenZimE
i belive you cant use the const keyword with an array because arrays in dot net cantnot be constant due to the way they are declared.

doing
const string[] string = {"yada",yadda","yaadda"};

is the same as doing
const string[] string = new string[] {"yada",yadda","yaadda"};

the only way your going to get any thing thats close to a constant array of some thing is to use the readonly keyword.
TheBluMage
TheBluMage
I've looked long and hard to find a way to create a const array in .Net too, but static readonly is the closest you'll be able to get. It's one of the few things I miss from C++. If what you want is just a readonly, immutable array, you could create a wrapper class (or struct) that would only allow you to get the elements from the array and not set them. It still won't have the small performance benefits of constants, but it will accomplish the same access restrictions.
realJJ
realJJ
Reference types cannot have the const modifiers. The only exception to it is the string type. And since Array is a reference type, you can only use the readonly modifier.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.