-1

I have a class of products and a machine manager class. Inside the machine manager class I have a private list of products with a getter and setter, I can access the list, but all of the properties inside the list are still private, so I cannot manipulate them in anyway.

Here is what I am trying to do

private List<Product> productsInsideMachine { get; set; }

When I try accessing the properties I get the error: inaccessible due to protection level.

//Retrieve all available proucts in machine
public void ListAvailableProducts()
{
    foreach (var product in productsInsideMachine)
    {
        Console.WriteLine(product.productName);
    }
}

One of the priorities of this exercise is to practice with private fields

Here is the product class

private string productName { get; set; }
private int productPrice { get; set; }
private int productQuantity { get; set; }

//Constructor
public Product(string name, int cost, int quantity)
{
    productName = name;
    productPrice = cost;
    productQuantity = quantity;
}
pfx
  • 20,323
  • 43
  • 37
  • 57

3 Answers3

2

Whatever fields need to be accessed in the Product class (this is the class you're trying to get the private data from) from outside the class, create a public property for those items. Example:

Before:

private int _someMember;

After:

public int SomeMember { get; private set; }

You should only expose the members publicly if it makes sense to do so. Making everything public in the class will make it difficult to use and it may even be used improperly. Also, from a design standpoint, it's cleaner to only expose a public "interface" for using the class. You should read about encapsulation and interfaces.

Also, the "private set" above means that you can get the value from outside the class, but not set it from outside the class. Unless you have a compelling need to set the value from outside the class, you should avoid doing so (again, read up on encapsulation and interfaces).

Andrew
  • 1,581
  • 3
  • 18
  • 31
1

Change the modifier from the Product class fields to public

You cannot access a private field from outside of it's own class.

you can read more about encapsulation Here

Vulpex
  • 1,041
  • 8
  • 19
-1

Make the list public cause thats the problem.

  public List<Product> productsInsideMachine { get; set; }
  • Please explain how making the list public will make the fields/properties of the class Product public. FYI, it doesn't, as this is not at all the problem. If this *was* the problem, then the OP wouldn't see `productsInsideMachine`, NOT `productsInsideMachine[0].productName` – Camilo Terevinto Nov 04 '18 at 19:35
  • I am also practicing with keeping things private, I shoul have mentioned this before. Thanks –  Nov 04 '18 at 19:36