Reputation: 3
I have an object array that is supposed to hold objects of different classes. I need to write down the attributes of those classes but don't know how to access them.
For example:
object[] NationalTeam;
possibly holding:
class Swimmer
class Runner
etc.
with different attributes. Can't access them with NationalTeam[i]
. Can it be done with overloading [] indexer? If yes, how?
Upvotes: 0
Views: 71
Reputation: 191058
You will have to either:
Cast them:
object teamMember = NationalTeam[0];
if (teamMember is Swimmer)
{
Swimmer swimmerTeamMember = (Swimmer)teamMember;
// Work with swimmer
}
// ... and so on
Add and implement an interface or base class such as ITeamMember
or TeamMember
.
interface ITeamMember { /* common properties */ }
class Swimmer : ITeamMember { /* ... */ }
ITeamMember[] NationalTeam;
Or use a combination of both.
Eric Lippert (one of the designers of C#) has a fantastic walk through to explain a very similar problem. I suggest that you read it. http://ericlippert.com/2015/04/27/wizards-and-warriors-part-one/
Upvotes: 4