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.
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();
public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(
new [] {
"string1",
"string2",
"string3"
}
);
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",
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With