Home Can I use a main class object as a parameter to find the subclass object?

# Can I use a main class object as a parameter to find the subclass object?

user11583
1#
user11583 Published in September 21, 2018, 8:04 am

I'm still kinda new at coding so I was wondering if/how this works?

//a class with armor with subclasses to say what part of the body it go's
public class Armor
{
//stuff that applies to all armor
}
{
}
public class ChestArmor : Armor
{
}
//etc

//the class that stores what  armor is equiped
public class MainCharacterEquipment
{
//the class of my maincharacter
public MainCharacter HeroEquipment { get; set; }

public ChestArmor ChestSlot { get; set; }
//etc
//a constructor that sets all to null

public void EquipArmor(Armor armor)
{
{
}
if (armor is ChestArmor)
{
ChestSlot = armor; //compile error -> Missing a cast?
}
//etc
}
}


If I do this it will ask if I'm missing a cast. From reading on this forum it seems that a subclass is a type of the mainclass but not the other way around.

To solve this I could make a method for each subclass of armor. Instead of using (Armor armor) as a parameter, I would use the (HeadArmor headArmor), (ChestArmor chestArmor), etc... But that seems tedious. I also read that there is a difference between typeof() and is but I dont realy understand that either. Preferably I would just cast the object armor to its subclass. Of course, the if function should check whether its not already the subclass (if that makes sense)

ps: There actualy are no instances of Armor objects. Only objects of subclasses are instantiated. (should it matter)

• try if ( armor is HeadArmor hArmor ) { HeadSlot = hArmor; } ... this will also do a cast if the type matches. Of course, there are more solutions to this... but start simple. – Fildor Feb 12 at 14:16
• @Korosevar Are you developing that stuff for Unity? If so pattern matching won't work – Tobias Theel Feb 12 at 14:20
• @ Fildor i get error: hArmor does not exist in current context – Korosevar Feb 12 at 14:21
• Why not make HeadSlot and ChestSlot both of type Armor? That is when polymorphism shines. – CodingYoshi Feb 12 at 14:23
• Which Platform is that? .Net framework 4.7 ? .Net Core? Unity? ... That might exclude some solutions ... – Fildor Feb 12 at 14:28

 You need to login account before you can post.
Processed in 0.375455 second(s) , Gzip On .