AnswerBun.com

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)
    {
        this.name = name;
        this.space = space;
        this.cost = cost;
        this.items = items;
    }

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

bag1.items.Add("Money");

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

How do I debug SwiftUI AttributeGraph cycle warnings?

5  Asked on December 30, 2021 by sindre-sorhus

       

RTD client in Python

1  Asked on December 30, 2021 by hunk

     

How to remove mongo specific fields from result (NodeJS, Mongoose)

5  Asked on December 30, 2021 by ararat-harutyunyan

     

Problem with ionic framework How can I solve?

0  Asked on December 30, 2021 by scar-fuentes

         

Random Forest Output

0  Asked on December 30, 2021 by charles-biwer

     

How to shift range of cells to unify values in rows

2  Asked on December 30, 2021 by jozef

 

Ask a Question

Get help from others!

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