Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
How to understand recursive generic type constraint in Unity C#?

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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>
{
}
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!