Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static readonly string arrays

Tags:

c#

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 facing any error, wanted to know is there any harm or performance issue for using like this?

like image 902
batwadi Avatar asked Mar 07 '10 05:03

batwadi


2 Answers

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.

like image 104
Jesse Hallam Avatar answered Oct 29 '22 22:10

Jesse Hallam


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"?

like image 40
Ben Voigt Avatar answered Oct 30 '22 00:10

Ben Voigt