c# initialize a static list in a class
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
.
Related videos on Youtube
Wolfkc
Updated on June 10, 2020Comments
-
Wolfkc almost 3 years
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 setup 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: Are 2 dimensional Lists possible in c#?
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 in valid 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.-
Jeroen Vannevel over 9 yearsYou cannot initialize the list with values that belong to the object. You have to create a new object and use the shorthand assignments there.
-
-
Wolfkc over 9 yearsAlmost, 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/…