CsharpLover
CsharpLover

Reputation: 47

how to add to the list an object of class property in c sharp

I cannot add class instances correctly to a List. It adds only the last object. And when I debug the List vocabulary shows only adding the last class instance. So by second looping it has two entries of second object, by third looping it has three entries of third object. What I am doing wrong. Here is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myVocabulary
{
    public class Word
    {
        string _original_word;
        string _translated_word;

        public string Original_Word
        {
            get
            {
                return this._original_word;
            }
            set
            {
                this._original_word = value;
            }
        }

        public string Translated_Word
        {
            get
            {
                return this._translated_word;
            }
            set
            {
                this._translated_word = value;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myVocabulary
{
    class Program
    {
        static List<Word> vocabulary = new List<Word>();
        static void Main(string[] args)
        {
            Word entry = new Word();

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("Enter word");
                entry.Original_Word = Console.ReadLine();
                Console.WriteLine("Enter Translation");
                entry.Translated_Word = Console.ReadLine();
                vocabulary.Add(entry);
            }           

        }
    }
}

Upvotes: 0

Views: 1324

Answers (1)

Gabe
Gabe

Reputation: 670

Try this - You need to create a new Word object with each iteration of your loop, otherwise you're just overwriting the same instance repeatedly.

namespace myVocabulary
{
    class Program
    {
        static List<Word> vocabulary = new List<Word>();
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                Word entry = new Word();
                Console.WriteLine("Enter word");
                entry.Original_Word = Console.ReadLine();
                Console.WriteLine("Enter Translation");
                entry.Translated_Word = Console.ReadLine();
                vocabulary.Add(entry);
            }           

        }
    }
}

Upvotes: 2

Related Questions