Reputation: 131
I want to add different sub classes which extends from the same base class into a List.
So this is the base class:
public class InteractionRequirement {
protected int requirementNumber;
public int RequirementNumber{
get{ return requirementNumber;}
set{ requirementNumber = value;}
}
}
And these are the subclasses:
public class ObjectInteraction : InteractionRequirement {
protected string objectName;
--getter and setter here--
}
public class CharacterInteraction: InteractionRequirement {
protected string characterName;
--getter and setter here--
}
public class AssetInteraction: InteractionRequirement {
protected string assetName;
--getter and setter here--
}
And I added them in one list:
List<InteractionRequirement> interactionRequirements = new List<InteractionRequirement>();
ObjectInteraction objectInteraction = new ObjectInteraction();
CharacterInteraction characterInteraction = new CharacterInteraction();
AssetInteraction assetInteraction = new AssetInteraction();
interactionRequirements.Add(objectInteraction);
interactionRequirements.Add(characterInteraction);
interactionRequirements.Add(assetInteraction);
But I can't seem to retrieve attribute values from the sub classes, there's an error.
string oName = interactionRequirement[0].ObjectName;
string cName = interactionRequirement[1].CharacterName;
string aName = interactionRequirement[2].AssetName;
Upvotes: 1
Views: 836
Reputation: 70728
That's because the interactionRequirements
collection is of type InteractionRequirement
not of the derived type (ObjectInteraction, CharacterIteraction or AssetInteraction).
Therefore, you'll need a cast.
string oName = ((ObjectInteraction)interactionRequirement[0]).ObjectName;
You can also use as
and check if the cast was successful.
var objectInteraction = interactionRequirement[0] as ObjectInteraction;
if (objectInteraction != null)
{
string oName = objectInteraction.ObjectName;
}
As an additional note, you may need to change the protection level of ObjectName
to public
so you can access it in the appropriate context (Outside of the class and derived classes).
Upvotes: 5