views:

91

answers:

4

I have the following repository that I use for unit testing:

public class MyTestRepository<T>
{
    private List<T> entities = new List<T>();

    public IQueryable<T> Entities
    {
        get { return entities.AsQueryable(); }
    }

    public T New()
    {
        //return what here???
    }

    public void Create(T entity)
    {
        entities.Add(entity);
    }

    public void Delete(T entity)
    {
        entities.Remove(entity);
    }
}

What do I return in the New() method?

I have tried this:

    public T New()
    {
        return (T) new Object();
    }

But that gives me the following exception when I run my unit test:

System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'MyCustomDomainType'.

Any idea on how to implement the New() method?

+1  A: 

Assuming type T has a public / default constructor, would this not correct the exception?

public T New()
{
    return new T();
}
djacobson
You can't assume, you have to enforce it using new() (as others have mentioned).
OJ
+9  A: 

You could add a constraint for the T type parameter:

public class MyTestRepository<T> where T : new() 

and return new T(); in the method.

Mehrdad Afshari
Yes - that works. Thanks for all the answers guys. I'm going to mark this answer as the correct answer because it got the most up-votes.
hungster
+2  A: 

You should change your repository definition by adding the new() constraint, like this:

public class MyTestRepository<T> where T : new()
{
    ...
}

This constrains types that can be used with MyTestRepository to those that have a default constructor. Now, in your New() method you can do:

public T New()
{
    return new T();
}
Ben
+1  A: 

That won't work as you're just creating an object, nothing else. How about creating the object with Activator:

return (T)Activator.CreateInstance(typeof(T));

See: http://msdn.microsoft.com/en-us/library/system.activator.aspx

steinar
Although this works, I would rather use "where T : new()" and return new T() as others are suggesting.
steinar
In cases like this any use of reflection is an indication you're doing something wrong :-) (more often than not).
OJ
As mentioned, I agree that his is not the way to go since the where condition can be used to ensure that the type can be newed. In other cases, reflection would be valid.
steinar