Search code examples
c#listclassconstructorinstance

C# How to store instances of a class in a list


I have a class named User. The class has a static property called Users which is a list to store all the users created. I want the users to be added to this list automatically when they are instantiated so I have included this in the constructor block in the User class.

I have written the below code, but when I create users with the constructor, they are not added to the Users list and the list remains empty.

Below is the code I have written.

public class User
{
    private static List<User> _users=new List<User>();
    private string _name;

    public User(string Name)
    {
        _name=Name;
        _users.Add(this);
    }
}

I know I can add each user to the list right after I create the instance of the User class. But I want to know if there is a way to do this automatically.

Also need to know whether it's better to have the list of users inside the User class, or the base class where I create each user.


Solution

  • I suggest using standard way to hold references of the created users.

    public class User
    {
        private string _name;
    
        public User(string Name)
        {
            _name = Name;
        }
    }
    
    var users = new List<User>();
    users.Add(new User("foo"));
    users.Add(new User("bar"));
    
    Console.Writeline(users.Count); // this will say 2!
    // you can now use your list of users.