I'm making a game in Unity and I'm using a sort of factory pattern where I need to create a Tile object of a specific type, and I'm not sure how to compare types in C#.
This is my code:
public T SpawnTile<T>(Vector3 startPosition) where T : Tile
{
Tile t;
if(T == MountainTile) // This line
{
t = new MountainTile();
}
if (T == WaterTile) // And this line
{
t = new WaterTile();
}
return (T)t;
}
I searched everywhere and all I found was the usage of obj is Type, but in my case I want to compare the generic type T.
I also tried Types.Equals(T, WaterTile) but it didn't work. Any suggestions?
CodePudding user response:
Of course, you can compare them by using typeof keyword:
public T SpawnTile<T>(Vector3 startPosition) where T : Tile
{
T t;
if(typeof(T) == typeof(MountainTile)) // This line
{
t = new MountainTile();
}
if (typeof(T) == typeof(WaterTile)) // And this line
{
t = new WaterTile();
}
return t;
}
But, as was mentioned in comments it's better to use new constraint if possible:
public T SpawnTile<T>(Vector3 startPosition) where T : Tile, new()
{
T t = new T();
// Other actions...
return t;
}
CodePudding user response:
do this work for you?
Tile t;
var type = T as Type
switch (type)
{
case Type _ when type == typeof(MountainTile):
t = new MountainTile();
break;
case Type _ when type == typeof(WaterTile):
t = new WaterTile();
break;
}