Thyl
Thyl

Reputation: 3

How to access different types of classes in a single object array in C#

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

Answers (1)

Daniel A. White
Daniel A. White

Reputation: 191058

You will have to either:

  1. Cast them:

    object teamMember = NationalTeam[0];
    
    if (teamMember is Swimmer)
    {
        Swimmer swimmerTeamMember = (Swimmer)teamMember;
        // Work with swimmer
    }
    // ... and so on
    
  2. Add and implement an interface or base class such as ITeamMember or TeamMember.

    interface ITeamMember { /* common properties */ }
    class Swimmer : ITeamMember { /* ... */ }
    ITeamMember[] NationalTeam;
    
  3. 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

Related Questions