Search code examples
c#unity-game-enginestring-comparison

How to compare generic types usnig c# language?


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?


Solution

  • 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;
    }