Home > Software design >  C# List cannot be accessed anywhere outside its method [closed]
C# List cannot be accessed anywhere outside its method [closed]

Time:09-17

I'm really new to programming in C# and have been following several tutorials online. I'm working on creating a small rpg-style console application game. I wanted an inventory system that can have items copied to it from a large library of possible items. I've followed the following advice for creating lists of objects (https://www.c-sharpcorner.com/UploadFile/mahesh/create-a-list-of-objects-in-C-Sharp/), and I've added objects with properties. However, I can't access these objects or properties from anywhere else in my code, despite everything being "public".

//Create library
public static void Library()
{
    List<Weapon> WeaponList = new List<Weapon>
    {
        new Weapon("Mace", 8),
        new Weapon("Spear", 8),
        new Weapon("Longsword",8)
    };

I've tried every combination of periods, parentheses, and brackets, but according to Visual Studio outside of Library() the WeaponList and all others lists in there don't exist. How can I get around this? If this is a stupid question, is there a resource I should go to to learn more about what I'm doing wrong?

CodePudding user response:

Please read others explanations of how methods works. Try something like this:

public List<Weapon> WeaponList;

//Create library
public static void Library()
{
    WeaponList = new List<Weapon>
    {
        new Weapon("Mace", 8),
        new Weapon("Spear", 8),
        new Weapon("Longsword",8)
    };
}

CodePudding user response:

Library() is a method you have to create a static class instead.

public static class Library
{
    public static  List<Weapon> WeaponList {get; set; } = new List<Weapon>
    {
        new Weapon("Mace", 8),
        new Weapon("Spear", 8),
        new Weapon("Longsword",8)
    };
}

you can use it

var weapons = Library.WeaponList;
  • Related