开发者

Static readonly string arrays

I am using static readonly string arrays in my web application. Basically array is having error codes and i have kept all similar error codes in one array and checking this array instead of checking each one in different constant string.

like

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

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

Note : I am not facin开发者_JAVA技巧g any error, wanted to know is there any harm or performance issue for using like this?


Try something like this instead:

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

You'll need to include the namespace System.Collections.ObjectModel in order to expose this object. ReadOnlyCollection only implements as getter and your array content cannot be changed.


Well, you should know that it is only the array reference that is readonly, not the array content. So if the array is public (and it sounds like it is), any part of the program could overwrite any or all of the messages, the only thing not possible is resizing the array.

Does that meet your definition of "harm"?


As Ben mentions, your array is still modifiable. It can't be changed to another array but the elements within it can be easily replaced. As an alternative you can make the array field private and expose it in a public property like so:

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

}


Kivin has a good idea.

You might see if constants in a static class would suit your needs better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜