Coding Screens with Generics


Mech Retriever Dev Blog

I finally got generics working with Screens in Mech Retriever.

It’s an effort I’d tried several times before–but there were always previously a combination of issues.

For those of you who don’t know, in C# Coding, Generics is a coding technique where you specify Type arguments for a class or method.  That makes it so that you can use that class or method for any type.  It’s kind of like using Interfaces, but more powerful in a way since you don’t need the types to implement any interface.  Everyone who’s done much C# coding has used generics via the List<T> type or the Dictionary<T> type.

The trick with Generics on Screens was twofold–first, I needed a good enough justification to use them.  Then I needed a way to keep a list of Screens in a collection. The justification ended up being the ability to cleanly specify a Screen for any GraphicalView type, so I could write a method AddGraphicalView(int playerId) that would handle creation and wiring-in of the right kind of view for a given player.  That reduced a lot of code duplication.

The collection problem was that I couldn’t find a way to specify a Queue of Screens that could be of any type.  The way around that was to have two classes–Screen, and ViewableScreen<T>.  The collection would be for Screens, and it would just happen that all screens are of typeViewableScreen.

So, Generics can be really helpful, just make sure you’re gaining something for your trouble and watch out for the gotchas around collections.

May you build the ultimate giant robot.

Like, Share, Subscribe, or Tweet us!

Check us out on Youtube or Deviantart!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s