is it possible to add a list to a structure?
14,943
Solution 1
Yes you can have a list in struct but you cannot initialise it with a field initialiser and instead you must use the constructor.
struct MyStruct
{
public List<string> MyList;
public int MyInt;
public MyStruct(int myInt)
{
MyInt = myInt;
MyList = new List<string>();
}
}
Solution 2
struct can have a constructor and you can instantiate the list in the constructor.
Solution 3
I am not an expert in C# but a structure is just a prototype of how your memory would look. You will have to declare a structure variable to be able to do "new list()" and assign it to a list variable.
something like struct test a; a.y = new list();
I have never programmed in C# so please convert my C syntax to C#.
Comments
-
Crash893 almost 2 years
Is it possible to add a list to a struct?
public struct test { public string x; list<string> y = new list<string>(); }
something like that?
ive been trying but im just not getting it
-
Matthew Flaschen almost 15 years"private List<object> y = new List<object>();" gives me "error CS0573: `test.y': Structs cannot have instance field initializers" Of course it could be done with a class...
-
Matthew Flaschen almost 15 yearsAlso note that you can not have a parameter-less constructor.
-
boctulus about 9 yearsThe point is... an struct should NOT reference mutable types (or collections of mutable entities)