27

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.

1
  • 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. Commented Oct 16, 2013 at 0:49

1 Answer 1

39

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Almost, i think this got it: public static List<ArchecturesClass> archs = new List<ArchecturesClass> { new ArchecturesClass() { architecturesId = "0", architecturesName= "x86"}, new ArchecturesClass() { architecturesId = "9", architecturesName= "x64"} }; Also found this ref which has a good example at bottom msdn.microsoft.com/en-us/library/vstudio/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.