views:

156

answers:

4

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

+1  A: 

struct can have a constructor and you can instantiate the list in the constructor.

Ali Shafai
+1  A: 

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#.

Aditya Sehgal
A: 

You can do that - declare a constructor for the struct and create a list instance in the struct constructor. You can't use an initializer as you proposed in your code snippet.

sharptooth
"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
Yeap, I tested it at the same time and updated the answer.
sharptooth
+4  A: 

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>();
    }
}
sipwiz
Also note that you can not have a parameter-less constructor.
Matthew Flaschen
I'm not sure what that means
Crash893