CreeperInATardis
CreeperInATardis

Reputation: 93

Create a new instance of a type from a variable

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).

Upvotes: 0

Views: 97

Answers (1)

rossipedia
rossipedia

Reputation: 59367

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());

Upvotes: 1

Related Questions