'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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yevhen Cherkes