Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant allocation of static readonly collection of strings

Tags:

c#

.net

I want to create a static ReadOnlyCollection with strings.

Is there any way to make this expression shorter or more elegant in some way?

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

I use this many times, but in different files.

like image 715
Andrey Rubshtein Avatar asked Jan 30 '12 09:01

Andrey Rubshtein


4 Answers

Another option is to use List<T> with a collection initializer, and the AsReadOnly method:

public static readonly ReadOnlyCollection<string> ErrorList = new List<String> {
    "string1",
    "string2",
    "string3",
  }.AsReadOnly();
like image 107
Jon Skeet Avatar answered Nov 16 '22 18:11

Jon Skeet


public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(
  new [] {
    "string1",
    "string2",
    "string3"
  }
);
like image 41
Frederik Gheysels Avatar answered Nov 16 '22 20:11

Frederik Gheysels


Array.AsReadOnly<T> and new[] can infer the contents of the array:

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

If you don't mind working with an interface, ReadOnlyCollection<T> implements several of them including IList<T>:

public static readonly IList<string> ErrorList = Array.AsReadOnly(
  new[] {
    "string1",
    "string2",
    "string3",
  }
);

Stylistically, I prefer to avoid multiple indentations for a single block:

public static readonly IList<string> ErrorList = Array.AsReadOnly(new[] {
  "string1",
  "string2",
  "string3",
});
like image 4
DBN Avatar answered Nov 16 '22 20:11

DBN


The most compact I think is:

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

The using directive is just here to reduce the amount of code in case you're using ReadOnlyCollection<string> a lot. If it's not the case, it won't reduce anything.

like image 3
ken2k Avatar answered Nov 16 '22 19:11

ken2k