Oskar Andersson
Oskar Andersson

Reputation: 13

Creating multiple inputs to a ClassList

So I have coded for a while I C# and learned the basics, one thing that always stops me is how I can create a class and then use a list for a user to input values.

I don't know if I'm totally off the chart with this code, the problem is that I don't understand why I can't use my newly created object of the class and add input to it. All help is appreciated

class Program
{
    static void Main(string[] args)
    {
        List<Citizen> listOfCitizens = new List<Citizen>();

        for (int i = 0; i < listOfCitizens.Count; i++)
        {


        Console.WriteLine("Enter Surname for the citizen:");
        listOfCitizens.SurName.add = Console.ReadLine();

        Console.WriteLine("Enter Lastname for the citizen:");
        listOfCitizens.Lastname.add = Console.ReadLine();

        Console.WriteLine("Enter age of the citizen:");
        listOfCitizens.age.add = int.Parse(Console.ReadLine());

        }
        Console.WriteLine($"Name {Citizen.SurName} {Citizen.LastName} {Citizen.age}");
        Console.Read();
    }
}

class Citizen
{
    public static string SurName{ get; set; }
    public static string LastName{get;set;}
    public static int age { get; set; }
}

Upvotes: 1

Views: 175

Answers (1)

David
David

Reputation: 219027

A list of something is not a something. Just like a basket of apples is not an apple. You don't eat the basket, you eat an item from the basket.

So when you create your list:

List<Citizen> listOfCitizens = new List<Citizen>();

You would then create an item to add to the list:

Citizen someCitizen = new Citizen();
someCitizen.SurName = "Smith";
// etc.

And then add it to the list:

listOfCitizens.Add(someCitizen);

Additionally, your Citizen is a little off. Those properties shouldn't be static. Not sure why you made them that way, but you should remove the static keyword from everything in your Citizen class.

Upvotes: 3

Related Questions