Static string arrays readonly

I use readonly string static strings in my web application. Basically the array has error codes, and I saved all the same error codes in one array and checked this array instead of checking each of them in a different constant string.

like

public static readonly string[] myarray = string[] {"232132132","31232132","123123123"} 

Please let me know if there is any harm when using readony static string arrays?

Note. I do not encounter any error, wanted to know if there is any harm or performance problem to use like this?

+4
source share
4 answers

Try something like this:

 public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>( new string[] { "string1", "string2", "stringn", } ); 

To open this object, you need to include System.Collections.ObjectModel namespace. ReadOnlyCollection implements only as a getter, and the contents of your array cannot be modified.

+10
source

Well, you should know that this is only a reference to an array, which is read-only, not the contents of the array. Therefore, if the array is publicly available (and it looks like it is), any part of the program can overwrite all or all messages, the only thing that is impossible is to resize the array.

Does this fit your definition of "harm"?

+5
source

As Ben mentions, your array is still being modified. It cannot be changed to another array, but the elements inside it can be easily replaced. Alternatively, you can make the array field private and expose it in a public property:

 public class MyClass { private static readonly string[] myArray = { ... }; private static readonly IList<string> myArrayReadOnly = Array.AsReadOnly(myArray); public static IList<string> MyArray { get { return myArrayReadOnly; } } } 
+3
source

Kivin has a good idea.

You can see if the constants in the static class will better suit your needs.

0
source

Source: https://habr.com/ru/post/1303374/


All Articles