Home > Back-end >  How to understand recursive generic type constraint in Unity C#?
How to understand recursive generic type constraint in Unity C#?

Time:03-10

While I understand generic types <T> and where clause for constraint, I was confused about the following code from Unity Tower Defense Template:

public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>

What's the purpose of restricting the type to be itself?

CodePudding user response:

It prevents you from doing this:

public class A
{
}

public class B : Singleton<A>
{
}

You will get a compile error. Due to the type constraint, you must write:

public class A : Singleton<A>
{
}

CodePudding user response:

Off the top of my head, one possible benefit of this is allowing methods to return the specific type. This is done by fluent style methods. Another example, obviously not applicable to the example you posted, is a Copy() method that returns a copy of the object as the derived type rather than as its base type. The method signatures of the Singleton< T> class you posted likely show where it uses the T parameter and likely hint at the reason why it uses this pattern.

  • Related