Home > Back-end >  How to consume List from another class
How to consume List from another class

Time:12-15

Whenever I give new when instantiating a class or list, will it be recreated? I'm having trouble consuming a list that I fed into another class. I'll give an example of my question to make it clearer:

I have the Customers class:


public class Clients
{
    public int id { get; set; }
    public string name { get; set; } 
}

and I have another class called:

public class CustomerList
{
    public List<Customers> dataCustomers;
}

these two are inside the same file or better same namespace.

Now I will feed this list through another Form1, so first I will instantiate it in this new form1:

CustomerList listCustomers = new CustomerList();

Now I'm going to feed the data into the class:

Customers customer = new Customers()
{
     id = 1,
     name = "Matthew"
}

and finally I will add the records inside the list:

listCustomer.dataCustomers.Add(customer);

Now I want to consume this list from another form/class, but I don't know how to do it. I tried instantiating it again in this new class. but it always returns saying that dataClientes was null, saying that the object is not being referenced. so well I couldn't understand this concept well, how to consume a list that I fed into another form/class.

In this form that I want to consume, I did it like this, I instantiated it:

CustomerList objCliente = new CustomerList();

and to test, I tried to play inside a message box, just to see the result.

MessageBox.Show(objCliente.dataCliente.ToString());

CodePudding user response:

To access the list of customers in the second form, you will need to pass a reference to the listCustomers object to the second form. You can do this by creating a constructor for the second form that accepts a CustomerList object as an argument, and then storing that object in a field of the second form. like that:

public class Form2
{
    private CustomerList listCustomers;

    public Form2(CustomerList listCustomers)
    {
        this.listCustomers = listCustomers;
    }
}

Then when you create an instance of "Form2" in your first form, you can pass a reference to the "listCustomers" object as an argument to the constructor:

Form2 form2 = new Form2(listCustomers);

You can then access the list of customers by calling the dataCustomers property on the listCustomers object.

CodePudding user response:

Make your property to be static, so that it can be accessed anywhere.

public class CustomerList
{
    static public List<Customers> dataCustomers;
}

The way to add new customer now become like this :

CustomerList.dataCustomers.Add(customer);

and to access it also same. You can access it using this way :

CustomerList.dataCustomers
  • Related