Goodquestion
Goodquestion

Reputation: 3

c# add item to list in object in list of objects

I've tried to work like: this one

Got an object class:

class Letter
{
    public char letter {get; set;}
    public List<int> posities { get; set; }

    public Letter()
    {
        posities = new List<int>();
    }
    
}

and want to add an int to the positions list by:

 letters.Add(new Letter
            {
                letter = a,
                posities.Add(i)                   
            });

But can't get it working, what am I doing wrong?? (btw: the letter a is added like expected, the problem is with adding the positie i).

Upvotes: 0

Views: 1877

Answers (3)

Ozan ERT&#220;RK
Ozan ERT&#220;RK

Reputation: 359

Lets rewrite your last code in order to clarify

var a = 'c';
var i = 0;
var letters = new List<Letter>(); 
var letter = new Letter();//Letter's constructor called and posties list initialized after that you can access posties member functions, like 'Add'
letter = a;
letter.posties.Add(i);
letters.Add(letter);

There are too many ways to write code, try to stay clear and do not put all the eggs in the same basket.

Upvotes: -1

Serge
Serge

Reputation: 43959

you have to use = to assign something when you use an object initializers - you can only set properties or fields, rather than call methods.

void Main()
{
    var a='a';
    var i=1;
    var letters = new List<Letter>();
    letters.Add(new Letter
    {
        letter = a,
        posities = new List<int> { i }
    });
    
}

otherwise maybe you will have to create a special constructor


    public Letter(char letter, int i)
    {
        letter=a;
        posities = new List<int> {i};
    }

Upvotes: 3

Goodquestion
Goodquestion

Reputation: 3

don't know why but this IS working:

letters.Add(new Letter
            {
                letter = a,                
            });

            letters[0].posities.Add(i);

Upvotes: 0

Related Questions