0

I've got this class:

public static class Repository<T> where T : class
{
    ....
}

I understand public and static and class and Repository<T>,but I'm not understanding this:

where T : class

Is Repository extending or implementing class? Or does the : class refer back to the type <T>?

!!ALSO!!:

And, if I have an abstract base class DataAccessBase that I want this class Repository to inherit, how do I do that?

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • 1
    It is a [Type Constraint](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters). – Alex K. Aug 24 '17 at 12:52
  • the declarations after `where T` refer to the `T` type. Also, you will instantiate it as any other generic class, the `: class` restricts the types to be reference types, not value types. – Gusman Aug 24 '17 at 12:53
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint – Koby Douek Aug 24 '17 at 12:53
  • The thing is , that putting the exact title in [google](https://www.google.co.il/search?q=What+does+this+mean%3A+ClassName%3CT%3E+where+T+%3A+class&oq=What+does+this+mean%3A+ClassName%3CT%3E+where+T+%3A+class&gs_l=psy-ab.3..33i160k1.106730.106730.0.107646.1.1.0.0.0.0.212.212.2-1.1.0....0...1.1.64.psy-ab..0.1.210.mu20ceGE3Zk) would have given all the inforamation you need quicker. – Ofir Winegarten Aug 24 '17 at 12:55
  • I probably worded the title wrong. Please see the ALSO part. "And, if I have an abstract base class DataAccessBase that I want this class Repository to inherit, how do I do that?" – Casey Crookston Aug 24 '17 at 12:59

1 Answers1

3

We are restricting it to consumable via a class as generic parameter and not to be used with struct (Value Types).

if we don't apply the constraint of the class on T, it would be usable with struct too and here the author has limited this generic class to usable on with T parameter with a reference type i.e. class as type parameter.

For more details, please refer to the MSDN docs on Type Constraint.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160