0

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

8
  • Please share a minimal reproducible example. Also read learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… . Commented Jul 17, 2021 at 13:44
  • "But can't get it working" Why not, what is the problem or the error? Commented Jul 17, 2021 at 13:44
  • @TimSchmelter it says: "The name posities does not exist in the current context. Invalid initializer member declarator" Commented Jul 17, 2021 at 13:51
  • letter = a, posities.Add(i) What is a and i ? Commented Jul 17, 2021 at 13:52
  • 1
    but wanted to keep it a minimal reproducible example. Minimal, perhaps. Reproducible - definitely not. Commented Jul 17, 2021 at 13:55

3 Answers 3

3

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};
    }
Sign up to request clarification or add additional context in comments.

Comments

0

don't know why but this IS working:

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

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

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.