Matze Katze
Matze Katze

Reputation: 11

Declaring an unknown Type in class declaration c#

Well, I should not be the first who asks this question. But I couldn't find the solution to my problem yet. Maybe I just don't know the exact term.

I am currently programming (in c#) a program that has to handle with gamers of different types.

i.e.:

public class Gamer {

  public int ID { set; get; }
  public string Name { set; get; }

public Gamer(int ID, string Name) 
{
  this.ID = ID;
  this.Name = Name;
}

then i am separating between different types of Players (e.g. Chess, GO, Golf) who have different attributes:

public class ChessPlayer : Gamer {

  public int ELORank { set; get; }

  public ChessPlayer(int ID, string Name, int ELORank) 
  {
    this.ID = ID;
    this.Name = Name;
    this.ELORANK = ELORank;
  }
}

public class TennisPlayer : Gamer {

  public int SinglesRank { set; get; }
  public int DoublesRank { set; get; }
  public bool LeftHanded { set; get; }

  public TennisPlayer(int ID, string Name,
                      int SinglesRank, int DoublesRank bool LeftHanded) 
  {
    this.ID = ID;
    this.Name = Name;
    this.SinglesRank = SinglesRank;
    this.DoublesRank = DoublesRank;
    this.LeftHanded = LeftHanded;
  }
}

Then I have a static class, where I write the currently participating Gamers:

public static class Game{
  public static int Type { set; get; } //0 = Chess, 1 = Tennis
  public static var Gamer { set; get; }
}

So that I can write on ButtonClick:

private void ButtonClick (Sender object, Event e)
{
  ArrayList Participants = new ArrayList;
  switch (Game.type)
  {
    case 0: //Chess
    {
      [...] //Add chess player to ArrayList
      break;
    Game.Gamer = Participants.ToArray(typeof(ChessPlayer)) as ChessPlayer[];
    }
    case 1: //Tennis
    {
      [...] //Add tennis player to ArrayList
      Game.Gamer = Participants.ToArray(typeof(TennisPlayer)) as TennisPlayer[];
      break;
    }

  }
}

Well I would like to do that but

public static var Gamer { set; get; }

is just not allowed because you can't have var in you class declaration.

That is why I am currently using the class AllGamer, that has every constructor and attribute of ChessPlayer and TennisPlayer and so on. And it is working. But I think that my original idea would be better.

I am quite new to c# and it is my first real OOP-project. So if you have any ideas I really would appreciate to hear/read them. Is there any possibility to use undetermined type or to determine the type at runtime (something like "var")?

Upvotes: 0

Views: 1444

Answers (1)

podiluska
podiluska

Reputation: 51514

Because both ChessPlayer and TennisPlayer are Gamer, you can create a property of type Gamer

 public Gamer TheGamer {get;set;}

An alternative is to define an Interface, say IGamer and make your Players implement that interface

 public IGamer TheGamer {get;set;}

Upvotes: 1

Related Questions