C# Generics and Type Safety at Runtime

1.2k views Asked by At

I'm not even really sure how best to phrase the question, but I'll see what I can do.

I have a goal, but I'm not sure how to, or if I even can, achieve it.

Let's say I have a type Sport. And then there's a Team<Sport> and a Player<Sport>. I'd like to make it such that any time I have a Team and a Player interact via methods, they can only do so if they have the same <Sport> type.

For instance: Team<Sport>.AddPlayer( Player<Sport> player) <- How can I make it so this can only be called when both Sports are the same type? If I have to derive new types from Sport, that could work, but I was hoping to do it based on instance at runtime.

I know the compiler won't know about the instances ahead of time, so I guess I'm wondering if there's some kind of type safety magic you can do to make it so I don't have to compare the types myself every time.

1

There are 1 answers

1
Sweeper On BEST ANSWER

You can't put instances into <> in C#. To achieve "type safety" you need to have actual "types" called Tennis, Hockey, Badminton etc. Otherwise the compiler cannot distinguish between sports.

Either you check whether the types of sports are the same at runtime, or you create subclasses of Sport, like Tennis, Badminton and Hockey. Since you want type safety at compile time, you should use the latter approach.

You can do something like:

var tennisTeam = new Team<Tennis>();
tennisTeam.AddPlayer(new Player<Tennis>());

Team can be defined like this:

class Team<TSport> where TSport : Sport {
    public void AddPlayer(Player<TSport> player) {
        // ...
    }
    // ...
}