C# - Constraints - where T : struct vs. where T : class

An unbound type parameter (no constraints)


  class MyClass<T>
  {
  }
  

T can be a value type or a reference type.


where T : struct

Example: the implementation of the generic value type System.Nullable<T> uses where T : struct to constrain its type parameter to a value type.


  class MyClass<T> where T : struct
  {
  }
  

T must be a value type.



  struct Nullable<T> where T : struct
  {
  }
  
where T : class

Example: the implementation of the generic class System.WeakReference<T> uses where T : class to constrain its type parameter to a reference type.


  class MyClass<T> where T : class
  {
  }
  

T must be a reference type.


  class WeakReference<T> where T : class
  {
  }
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath