user1621127
user1621127

Reputation: 301

C# Reaching objects from a different class

I'm learning C# and I'm trying to make a game and I have a problem. I have two classes that I call Item and Weapon, Weapon looks something like this:

class Weapon : Item
{ 
    int damage; 
    int durability;

    public void asd()
    {
        Weapon shortSword = new Weapon();
        shortSword.dmg = 5;
        shortSword.durability = 20;
        Weapon woodenBow = new Weapon();
        woodenBow.dmg = 3;
        woodenBow.durability = 15;
    }
 }

Then I have another class containing different methods, one of them is called when the player walks on an item and its supposed to randomize that item. But I can't reach the objects in Weapon from this other class. How do I reach them, or solve this problem?

Upvotes: 0

Views: 577

Answers (1)

Mark Byers
Mark Byers

Reputation: 837996

There is a problem with your design. The method that creates weapons shouldn't be an instance method on the Weapon class. It could perhaps be a static method, or perhaps even a method on some other class.

Your method should return the weapons in a collection or as an IEnumerable.

public class Weapon : Item
{
    public int Damage { get; set; }
    public int Durability { get; set; }

    // Consider moving this method to another class.
    public static IEnumerable<Weapon> CreateWeapons()
    {
        List<Weapon> weapons = new List<Weapon>();

        Weapon shortSword = new Weapon { Damage = 5, Durability = 20 };
        weapons.Add(shortSword);

        Weapon woodenBow = new Weapon { Damage = 3, Durability = 15 };
        weapons.Add(woodenBow);

        return weapons;
    }
}

I also used the object initializer syntax to make the code more concise, and tidied up some of your method/property naming.

Upvotes: 5

Related Questions