Search code examples
c#.net.net-micro-framework

Initializing ArrayList with constant literal


Can the ArrayList below be initialized directly without the need for aFileExt string array?

private static string[] aFileExt = 
     {"css", "gif", "htm", "html", "txt", "xml" };
private System.Collections.ArrayList alFileTypes =
     new System.Collections.ArrayList(aFileExt);

The line below is the goal, but my .Net Compiler does not like it:

private static System.Collections.ArrayList alFileTypes = 
     new System.Collections.ArrayList({"css","gif","htm","html","txt","xml"});

I am using the .net Micro Framework and thus do not have access to generic types.


Solution

  • C# 1 or 2:

    private static ArrayList alFileTypes = 
         new ArrayList(new string[] {"css","gif","htm","html","txt","xml"});
    

    C# 3 using an implicitly typed array:

    private static ArrayList alFileTypes = 
        new ArrayList(new[] {"css","gif","htm","html","txt","xml"});
    

    C# 3 using a collection initializer:

    private static ArrayList alFileTypes = 
        new ArrayList{"css","gif","htm","html","txt","xml"};
    

    Or create your own helper method:

    public static ArrayList CreateList(params object[] items)
    {
        return new ArrayList(items);
    }
    

    then:

    static ArrayList alFileTypes = CreateList("css","gif","htm","html","txt","xml");
    

    Any reason why you're not using the generic collections, btw?