I got class Weapon and class Shield (both inherited from Item class)
public class Weapon : Item
{
public int Damage;
public int Range;
}
public class Shield : Item
{
public int DamageAbsorb;
}
And I wand Unit to have variable RightHandItem and LeftHandItem, so that he can take weapon and a shield, two weapons (or even two shields)
How should I do that, as I can’t define RightHandItem as Weapon (because then he won’t be able to take a shield), as well as I can’t define it as Shield ((because then he won’t be able to take two weapons). Also I can’t define it as Item, because then I won’t be able to use Damege or DamageAbsorb properties.
So basically, I don’t know beforehead, whether it will be Weapon or Shield, what should I do?
When you say, " Also I can’t define it as Item, because then I won’t be able to use Damege or DamageAbsorb properties", that isn’t true. You can.
Since both Weapon and Shield are Items, the combination of all public (and protected ) parent variables and methods are available to these derived classes. Within the methods of Weapon, for example, any public member of Item is just as available as Damage and Range.
What might puzzle you is what to do when what you have is a reference to an Item, without knowing if that item is a Weapon or a Shield. From that perspective, the perspective of the Item, you don’t have immediate access to the members specific to Shields or Weapons. There are many answers, but among them you should resist any tendency to try to give Item knowledge of Weapons or Shields. That violates the notion of making Item a base class that operates only that which is appropriate to both Weapons and Shields, which is, in fact, handedness.
So, if you want to act as a Shield from within a method of Item, use an abstract method in Item that provides a specific override in Shield and Weapon. Look into abstract classes and methods to learn how, it is the magic you’re looking for.
You can resort to casting, but that’s considered naive and generally ignores what abstract methods do for you.