I want to initialize a static collection within my C# class – something like this:
public class Foo { private static readonly ICollection<string> g_collection = ??? }
I’m not sure of the right way to do this; in Java I might do something like:
private static final Collection<String> g_collection = Arrays.asList('A', 'B');
is there a similar construct in C# 2.0?
I know in later versions of C#/.NET you can do collection initializers (http://msdn.microsoft.com/en-us/library/bb384062.aspx), but migration isn’t an option for our system at the moment.
To clarify my original question – I’m looking for a way to succinctly declare a simple static collection, such as a simple constant collection of strings. The static-initializer-style way is also really good to know for collections of more complex objects.
Thanks!
If I fully understand your question, it seems some others have missed the point, you’re looking to create a static collection in a similar manner to Java in that you can declare and populate in a single line of code without having to create a dedicated method to do this (as per some of the other suggestions). This can be done using an array literal (written over two lines to prevent scrolling):
This both declares and populates the new readonly collection with the item list in one go. Works in 2.0 and 3.5, I tested it just to be doubly sure.
In 3.5 though you can use type inference so you no longer need to use the string[] array which removes even more keystrokes:
Notice the missing ‘string’ type in the second line line. String is automatically inferred from the contents of the array initializer.
If you want to populate it as a list, just change up the new string[] for new List a la:
Of course, because your type is IEnumerable rather than a specific implementation, if you want to access methods specific to List< string> such as .ForEach(), you will need to convert it to List:
But it’s a small price to pay for migratability [is that a word?].