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!

Related Questions

Appending a list in a list using a for loop

2  Asked on November 22, 2021 by syed-ahmed


Regular expression to find Specific character in a string

4  Asked on November 22, 2021 by user3061338


laravel count records based on each single date

1  Asked on November 22, 2021 by gulzar-ali


Change one property in CSS

2  Asked on November 22, 2021 by darek


Splitting values in a list and making variables of them

1  Asked on November 22, 2021 by premier12


JSX fragment has no corresponding closing tag

1  Asked on November 22, 2021 by chinwe-watkins


How to slow down window.location.href on AJAX request

3  Asked on November 22, 2021 by agiftel-longwave


Why list initialization disallow narrowing?

0  Asked on November 22, 2021 by alan-jian


How can i remove object from nested array?

2  Asked on November 22, 2021 by trajce12


How to save model architecture in PyTorch?

3  Asked on November 22, 2021


Ask a Question

Get help from others!

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