public interface IPerson
{
int Age { get; set; }
}
public class PersonRepository<T> where T : IPerson
{
private T m_person;
public PersonRepository(T person)
{
this.m_person = person;
}
public void Save()
{
// The Age property is available
if (this.m_person.Age > 65)
{
// Save to free bus pass database...
}
}
}
Wednesday, July 21, 2010
You Gotta Constrain to Expand...
When you create a Generic class and constrain the Type parameter T, you are actually increasing the number of operations available. I know it sounds like a contradiction but it makes sense when you think about it. By constraining my Type parameter with an Interface for example, I get access to all the operations that Interface defines. If you do not apply a constraint then you are limiting yourself to operations on System.Object!
Quick example...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment