tags:

views:

49

answers:

1

I really don't know if this is a C# thing or an asp.net thing. I was looking at this article: http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/ and ran into this line:

public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class

I'm fairly new to C#/ASP.NET so I don't fully understand this line. What does the "where TEntity : class" do? I have never created a class with a "where clause" (is that even what it's called).

+3  A: 

It's using generics (C# thing, nothing to do with ASP.NET).

<TEntity> is a generic type parameter, meaning you must specify the type of the GenericRepository.

Like this:

var repo = new GenericRepository<Person>();

The where clause says the type you supply must be a class.

It's called a Derivation Constraint. It basically tells the compiler to enforce this constraint.

If you changed it to where TEntity : int, the above code would fail.

You would need this:

var repo = new GenericRepository<int>();

A note on <TEntity>, this is not a keyword/reserved word. You could easily change it to <FooBar> and where FooBar : class. It has the T to indicate generics, and Entity to specify the Repository works off an Entity.

Change the generic type parameter to whatever makes sense to you and your code.

By the way - that article is like my bible at the moment. :)

RPM1984
I see. So the "where clause" can be used to enforce that the provided object is or is a subclass of whatever the item is. In this case it's "class" so any class could be the generic. So if I were to do "where <TEntity> : IList" it would only accept classes that implement the IList interface; correct?
William
@William - exactly right. Spot on. We use to generics to avoid repetition. If you didn't use the type parameter - you would need to create a PersonRepository, CustomerRepository, etc repeating code.
RPM1984