An object reference is required for a non-static field, method or property

This is the first time I work with lists, and it seems I don’t understand. I have a Customer class with a list of clients as a property in the Customer class (can this be done like this?)

public class Customer
{
    private List<Customer> customers = new List<Customer>();

    public List<Customer> Customers
    {
        get { return customers; }
        set { customers = value; }
    }

In my program, I add to this list of clients, like this:

Customer C = new Customer();
Customer.InputCustomer(C);
C.Customers.Add(C);

Now I need to show customers on this list. I added the AllCustomers function to the client class as follows:

public static void AllCustomers()
    {
        foreach (Customer customer in Customers) //Fail on "Customers"
        {
            Console.WriteLine("Customer ID: " + customer.ID);
            Console.WriteLine("Customer Name: " + customer.FullName);
            Console.WriteLine("Customer Address: " + customer.Address);
            Console.WriteLine();
        }
    }

But I get this error in the foreach statement:

An object reference is required for a non-static field, method or property 'AddCustomerList.Customer.Customers.get'

Like I said, this is the first time I use List, maby I don’t get it right? Can anyone help me please!

+3
source share
3

, Customers static.

, :

public void AllCustomers()
{
    // ...

(.. )

Customers Customers:

private static List<Customer> customers = new List<Customer>();

public static List<Customer> Customers
{
    get { return customers; }
    set { customers = value; }
}
+5

, AllCustomers() . "", , .

+3

As Gonzalo says , you need to remove staticfrom the method AllCustomers.

Alternatively, you can pass the customer list to the AllCustomers method, which can remain static.

public static void AllCustomers(List<Customer> customers)

However, I am curious why you have a list of customers within the customer class - is it because your customers have their own customers?

+2
source

Source: https://habr.com/ru/post/1766137/


All Articles