25

What I'm trying to have is a 2D global list initialized with strings. If I only wanted a simple list I could just initialize the list with strings separated by a comma like this

public static readonly List<string> _architecturesName = new List<string>() {"x86","x64" }; 

I have set up a static class Globals, in this class I'm adding a List based on another class ArchitecturesClass to be used as fields for the list similar to what was done here

public class ArchecturesClass
{  
    public string Id { get; set; }
    public string Name { get; set; }
}

// test1 : 
public static readonly List<ArchecturesClass> ArchitectureList =  new List<ArchecturesClass>() { "2", "9"}; 
    
// test2 : 
public static readonly List<ArchecturesClass> ArchitectureList = new List<ArchecturesClass>() 
    {
        architecturesId = "2",
        architecturesName = "3"
    };

The error on the strings is that the collection initialize has some invalid arguments and In the end, I want all classes in the project to be able to read something like Globals.ArchtecutreList.ID and a matching Globals.ArchtecutreList.Name; and I would like to initialize this in the global class without being in a method.

KiynL
  • 4,097
  • 2
  • 16
  • 34
Wolfkc
  • 353
  • 1
  • 3
  • 4
  • 1
    You cannot initialize the list with values that belong to the object. You have to create a new object and use the shorthand assignments there. – Jeroen Vannevel Oct 16 '13 at 00:49

1 Answers1

35

The syntax

new List<ArchecturesClass>() {architecturesId = "2",
                              architecturesName = "3"};

should probably be

new List<ArchecturesClass>() { new ArchecturesClass>() { architecturesId = "2",
                              architecturesName = "3"}};

Collection initializers expect you to provide instances of the type contained in your list.

Your other attempt

public static readonly List<ArchecturesClass> ArchitectureList = 
       new List<ArchecturesClass>() { "2", "9"}; 

fails because "2" and "9" are strings, not instances of ArchitecturesClass.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Almost, i think this got it: public static List archs = new List { new ArchecturesClass() { architecturesId = "0", architecturesName= "x86"}, new ArchecturesClass() { architecturesId = "9", architecturesName= "x64"} }; Also found this ref which has a good example at bottom http://msdn.microsoft.com/en-us/library/vstudio/bb384062(v=vs.100).aspx – Wolfkc Oct 16 '13 at 16:06