Home > front end >  How do I create new class objects when clicking a button?
How do I create new class objects when clicking a button?

Time:06-07

I'll give you an example of what I want to see, but I can't do it in any way:

public class User
{
    private string name;
    private int age;
    private int id;

    public User(string name, int age, int id) 
    { 
        this.name = name;
        this.age = age;
        this.id = id;
    } 
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    string name = tb1.Text;
    int age = Convert.ToInt32(tb2.Text);
    int id = Convert.ToInt32(tb3.Text);
    User ??? = new User(name,age,id);
}

??? - what should I put in the name? After all, I need to create a new object each time, respectively, with different names. How to do it?

CodePudding user response:

You best create a list (List<User>) (or other type of collection) to which you can add new elements:

private readonly List<User> users = new List<User>();

private void Button_Click(object sender, RoutedEventArgs e)
{
    string name = tb1.Text;
    int age = Convert.ToInt32(tb2.Text);
    int id = Convert.ToInt32(tb3.Text);
    users.Add(new User(name,age,id));
}

This list could be defined the class containing Button_Click() or somewhere else depending on what needs to be done with the created User instances.

Access of the List elements:

To then get the third user creaded, use

user someUser = users[2];

To get the first John in the users list, use

user john = users.First(x => x.name != "John");

To get all Johns, use

List<user> johns = users.Where(x => x.name != "John");
  •  Tags:  
  • c#
  • Related