Crash893
Crash893

Reputation: 11702

is it possible to add a list to a structure?

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

Upvotes: 7

Views: 21508

Answers (4)

sipsorcery
sipsorcery

Reputation: 30699

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>();
    }
}

Upvotes: 8

sharptooth
sharptooth

Reputation: 170469

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.

Upvotes: 1

Aditya Sehgal
Aditya Sehgal

Reputation: 2883

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

Upvotes: 1

Ali Shafai
Ali Shafai

Reputation: 5161

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

Upvotes: 1

Related Questions