virtualghost
virtualghost

Reputation: 33

Cannot add items to a Dictionary from within the class

I am working on a learning project in which I am trying to learn better practices. I have a class, Player, the Player among other things has Dictionary called Items, where items can be stored. The Player is initialized with just a Name and an Age, the Dictionary is supposed to be empty at the initialization of the Player.

Alongside the story, the Player can get items which will be stored in the inventory, so I am trying to create a method that can be called to do this, however I face the following issue:

If the method is not static, it cannot be called from outside the class with the following error:

An object reference is required for the non-static field, method, or property 'Player.AddItems(int, string)'.

If the method is static, it does not see the Items Dictionar with the following error:

An object reference is required for the non-static field, method, or property 'Player.Items'.

I am trying to call it from the main function (will become a class later) with:

Player.AddItems(0, "Wallet");.

Any suggestions are appreciated.

class Player
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Dictionary<int, string> Items { get; set; }

        public float Damage { get; set; }

        public float Health { get; set; }

        public Player(string Name, int Age)
        {
            this.Name = Name;
            this.Age = Age;
            this.Items = new Dictionary<int, string>();
            this.Damage = 0;
            this.Health = 20;
        }

        public void AddItems(int key, string item)
        {
            this.Items.Add(key, item);
        }

    }

Upvotes: 0

Views: 100

Answers (1)

Mihir Dave
Mihir Dave

Reputation: 4014

An object reference is required for the non-static field, method, or property 'Player.AddItems(int, string)'

You need to create an object first to call a non-static method of a class.

Player p = new Player("John", "25");
p.AddItems(1, "Data");

An object reference is required for the non-static field, method, or property 'Player.Items'.

You can't access non-static members from static methods

PS: You can assign default values to properties directly.

class Player
{
    public Player(string Name, int Age) : this()
    {
        this.Name = Name;
        this.Age = Age;
    }

    public string Name { get; set; }

    public int Age { get; set; }

    public Dictionary<int, string> Items { get; set; } = new Dictionary<int, string>();

    public float Health { get; set; } = 20;

    public float Damage { get; set; }

    public void AddItems(int key, string item)
    {
        this.Items.Add(key, item);
    }

}

Upvotes: 1

Related Questions