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");
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
2 Asked on December 30, 2021 by nitneuq
5 Asked on December 30, 2021 by sindre-sorhus
2 Asked on December 30, 2021
2 Asked on December 30, 2021 by jayjona
3 Asked on December 30, 2021 by shyam-nair
1 Asked on December 30, 2021
1 Asked on December 30, 2021 by i-shm
4 Asked on December 30, 2021 by learning-php
5 Asked on December 30, 2021 by ararat-harutyunyan
2 Asked on December 30, 2021
3 Asked on December 30, 2021 by antimonit
android android progressbar loading material components android progress bar
1 Asked on December 30, 2021 by mismas
0 Asked on December 30, 2021 by scar-fuentes
2 Asked on December 30, 2021 by ulugbek
0 Asked on December 30, 2021 by kanna
1 Asked on December 30, 2021
1 Asked on December 30, 2021
Get help from others!
Recent Answers
Recent Questions
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP