Showing posts with label generics. Show all posts
Showing posts with label generics. Show all posts

Thursday, July 22, 2010

Serializing Generic Types

There is no way currently of constraining a Generic type to ensure it is serializable at compile-time. However, there is a quick and easy way to check.


if (!typeof(T).IsSerializable)
{
throw new ArgumentException("type is not serializable");
}

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...



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...
}
}
}