Ali
Ali

Reputation: 39

How to refer to an array without creating a new one?

I want to refer to my USERS list in a form without having to create a new instance of the class the list is stored in as it creates a new list.

The LoginHandler class where the list is created and is added to.

namespace BG
{
    public class LoginHandler
    {
         public List<User> users = new List<User>();

         public LoginHandler()
         {
            users = new List<User>();
         }

The form will consist of a for loop which loops to the count of items in the list so i need to refer back to it but do not want to have to create a new instance of class its in because that makes a new list which i do not want.

Upvotes: 0

Views: 59

Answers (1)

Skye MacMaster
Skye MacMaster

Reputation: 914

I think what you want is a property that returns a reference to a IEnumerable object.

public class LoginHandler
{
    private List<User> users = new List<User>();
    public IEnumerable<User> Users { get { return users; } }
}

Then you can access the property without creating a copy or exposing the internal data members.

LoginHandler handler = new LoginHandler();
foreach (var user in handler.Users)
{
}

Upvotes: 1

Related Questions