How do you put a list inside of an object C#?

Stack Overflow Asked by Forrest on August 8, 2020

New to C#, sorry if the wording is a little off. I want to make one of my fields in an object as a list. My below code does not let me access the list.

class Bag
    public string name;
    public int space;
    public int cost;
    List<string> items = new List<string>();

    public Bag(string name, int space, int cost, List<string> items)
    { = name; = space;
        this.cost = cost;
        this.items = items;

I am not able to use items when using the below code:


One Answer

You forgot to make it public

public List<string> items = new List<string>();

For more information about why you need to do this, see Access Modifiers (C# Programming Guide)

public: The type or member can be accessed by any other code in the same assembly or another assembly that references it.

Additionally, you should prefer properties over fields for public access

public string name { get; set; } 
public int space { get; set; } 
public int cost { get; set; } 
public List<string> items { get; set; } = new List<string>();

Correct answer by TheGeneral on August 8, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP