0

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?

1 Answer 1

4

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/

Sign up to request clarification or add additional context in comments.

4 Comments

Can't do 'object teamMember = NationalTeam[0];' becouse National team is still empty. It's not static.
I'm a newbe, need some clues.
@Thyl that's a separate question. You will have to narrow down how the data is stored
@Thyl i would ask that in a separate post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.