Kili
Kili

Reputation: 37

C# Why does adding objects to my List<> replace all other items?

I am trying to read input from the console and create objects of my own datatype Word and add them to a List. However everytime I add a new one all previous ones get replaced.

The Loop:

while (!QuitInput(wordInput.ToLower()))
{
    ...handle invalid input...
    else
    {
        try
        {
            ReadWordFromConsole(languages[0], languages[1], wordInput);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
    wordInput = Console.ReadLine().Trim(' ', ';');
}

The Method:

private static void ReadWordFromConsole(string language1, string language2, string input)
{
    var splitInput = input.Split(';');
    for (int i = 0; i < splitInput.Length; i++)
        splitInput[i] = splitInput[i].Trim(' ');
    if (splitInput.Length < 2)
    {
        if (!input.Contains(';'))
            throw new ArgumentException("Separate with ';'");
        throw new ArgumentException("Invalid input. 'h' for help.");
    }

    var translationList = new List<string>();
    for (int i = 1; i < splitInput.Length; i++)
        translationList.Add(splitInput[i]);


    var word = new Word(language1, language2, splitInput[0], translationList);
    _loadedWords.Add(word);
}

Word class:

private static string _language;

public Word(string language, string translationLanguage, string text, List<string> translations)
{
    Language = language;
    TranslationLanguage = translationLanguage;
    Text = text;
    Translations = translations;
}

public string Language
{
    get
    {
        return _language;
    }
    set
    {
        if (string.IsNullOrEmpty(value))
            throw new ArgumentException("Language cannot be empty");
        _language = value;
    }
}
...

The global list declared in the same class as ReadWordFromConsole:

private static List<Word> _loadedWords = new List<Word>();

When researching I discovered some posts saying that you cannot use the same instance of the object in the loop. But am I not creating a new one every time ReadWordFromConsole is called?
What would I have to change in order for it to work and not replace previous words?

Upvotes: 0

Views: 346

Answers (1)

Hans Kesting
Hans Kesting

Reputation: 39338

With a static field as backing store of a property

private static string _language;

even if it is an instance property, you are effectively having just a single location where all your Word instances store/get their Language.

Solution: just remove that static.

Upvotes: 2

Related Questions