0

Okay, so I have a dictionary of types int and Tile. I have a class called TileManager that I'm designing to return a NEW instance of a certain tile. Right now this is what I have.

public class TileManager
{
    private Dictionary<int, Tile> _registeredTiles = new Dictionary<int, Tile>();

    public Tile GetNewTile(int id)
    {
        // Here, I need to return a new instance of the tile at the given key. I want
        // something like this: return new _registeredTiles[id].GetType();
    }
    . . .
}

The problem is, I can't just create a new Tile class, because it will be holding different classes other than tiles (it will be holding children of Tile).

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 2
    Are you saying you have multiple inheritance of Tile something like SquareTile, CircleTile..etc? or you want to clone the instance stored in _registeredTiles – OKEEngine Sep 22 '13 at 23:17
  • You could use a Factory. See this post: http://stackoverflow.com/questions/3578648/type-casting-and-the-factory-pattern – Caleb Sep 22 '13 at 23:22
  • "holding different classes" implies `Dictionary` (with types restricted to `Tile` and derived ones), but your post shows different declaration `Dictionary`. Which one is correct? – Alexei Levenkov Sep 22 '13 at 23:35
  • By that I meant I have different classes inherited from Tile. – CreeperInATardis Sep 22 '13 at 23:48

1 Answers1

1

The simplest solution would be to use Activator.CreateInstance();

You can pass it a type and an array of constructor arguments if required:

return (Tile)Activator.CreateInstance(_registeredTiles[i].GetType());
rossipedia
  • 56,800
  • 10
  • 90
  • 93