简体   繁体   中英

Adding users to a list via user input C#

I have a users class which I would like to use to create a list of users until the user no longer wishes to. I don't know how to get input from console. I've deleted my main code as it is a confusing mess and would prefer to start from scratch. My Users class is below.

class Users
{
    List<Users> _userList = new List<Users>();

    private string _name;
    private int _age;
    private string _address;
    private string _phone;

    public Users(string name, int age, string address, string phone)
    {
        _name = name;
        _age = age;
        _address = address;
        _phone = phone;
    }

    public string GetName()
    {
        return _name;
    }

    public void SetName(string name)
    {
        _name = name;
    }

    public int GetAge()
    {
        return _age;
    }

    public void SetAge(int age)
    {
        _age = age;
    }

    public string GetAddress()
    {
        return _address;
    }

    public void SetAddress(string address)
    {
        _address = address;
    }

    public string GetPhone()
    {
        return _phone;
    }

    public void SetPhone(string phone)
    {
        _phone = phone;
    }

}

Cheers

First remove List from your Users class and rename it to User.

public class User
{
    private string _name;
    private int _age;
    private string _address;
    private string _phone;

    public User(string name, int age, string address, string phone)
    {
        _name = name;
        _age = age;
        _address = address;
        _phone = phone;
    }

    //...
}

Then declare List of User classes in console Program class and add new user to the list. Set user properties according to the user console input.

List<User> _userList = new List<User>();

static void Main(string[] args)
{
    Console.Write("Name: ");
    string name = Console.ReadLine();

    Console.Write("Age: ");
    int age = int.Parse(Console.ReadLine());

    Console.Write("Address: ");
    string address = Console.ReadLine();

    Console.Write("Phone: ");
    string phone = Console.ReadLine();

    User user = new User(name, age, address, phone);
    _userList.Add(user);
}

Firstly, take note that List<Users> _userList = new List<Users>(); is unneeded in your class. You're not using it anywhere. A List<T> structure is a good way to store multiple users - just replace T with a type that represents a user. You should change the name of your class to represent a single user ( User would be a good idea here) and use a List<User> outside of the class.

Take a look at this contrived example, where user has one string property - the name of the user. It enables you to add multiple users to a list with names of your choosing and then prints each of the names in a new line. Note that I used an auto-implemented property to store the user's name.

class User
{
    public User(string name)
    {
        Name = name;
    }

    public Name { get; private set; }
}   

public static void Main()
{
    List<User> users = new List<User>();
    bool anotherUser = true;
    while (anotherUser)
    {
        Console.WriteLine("Please specify a name.");
        string userName = Console.ReadLine();
        User user = new User(userName);
        users.Add(user);
        string next = Console.WriteLine("Do you want to add another user (type Y for yes)?");
        anotherUser = (next == "Y");
    }

    Console.WriteLine("\nNames of added users:");
    foreach(User u in users)
    {
        Console.WriteLine(u.Name);
    }

    Console.ReadKey();
}    

Of course you have to expand on this answer to really get what you want. This is merely a point of reference.

Let us consider a simple use case to get a basic understanding:

As others suggested already you can improve the User class as shown below and C# has a concept of Auto-Implemented Properties and the compiler will handle the getter/setter code generation behind the scenes for you and so at least your code is clean enough!! Again at times you may need to have constructor injected property values or explicit methods to set values and I am not going into that.

public class User
{
   public string Name { get; set; }
   public int Age { get; set; }

   //Other properties/indexers/delegates/events/methods follow here as required. Just find what all these members are in C#!!
}

Code to accept user input:

static void Main(string[] args)
{
     List<User> users = new List<User>();

     char createAnotherUser = 'N';

     do
     {
          var user = new User();
          int age;

          Console.Write("\nUser Name: ");
          user.Name = Console.ReadLine();

          Console.Write("Age: ");
          string ageInputString = Console.ReadLine();

          //Validate the provided age is Int32 type. If conversion from string to Int32 fails prompt user until you get valid age.
          //You can refactor and extract to separate method for validation and retries etc., as you move forward.
          while (!int.TryParse(ageInputString, out age)) //Notice passing parameter by reference with 'out' keyword and it will give us back age as integer if the parsing is success.
          {
               Console.Write("Enter a valid Age: ");
               ageInputString = Console.ReadLine();
          }

          //Accept other data you need and validate if required

          users.Add(user); //Add the user to the List<User> defined above

          //Confirm if another user to be created
          Console.Write("Do you want to create another User[Y/N]? : ");
          createAnotherUser = char.ToUpper(Console.ReadKey(false).KeyChar); //Compare always upper case input irrespective of user input casing.

    } while (createAnotherUser == 'Y');

You can learn more about passing variable by reference using out keyword in MSDN

Hope this provide you some idea...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM