tags:

views:

285

answers:

4

Hi guys,

I'm having a bit of trouble writing a class that uses generics because this is the first time that I have had to create a class that uses generics.

All I am trying to do is create a method that converts a List to an EntityCollection.

I am getting the compiler error: The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Objects.DataClasses.EntityCollection'

Here is the code that I am trying to use:

    public static EntityCollection<T> Convert(List<T> listToConvert)
    {
        EntityCollection<T> collection = new EntityCollection<T>();

        // Want to loop through list and add items to entity
        // collection here.

        return collection;
    }

It is complaining about the the EntityCollection collection = new EntityCollection() line of code.

If anyone could help me out with this error, or explain to me why I am receiving it I would greatly appreciate it. Thanks.

+3  A: 

You are likely getting that error because the EntityCollection constructor requires T to be a class, not a struct. You need to add a where T:class constraint on your method.

Yuriy Faktorovich
+4  A: 

You must constrain the type parameter T to be of reference type :

public static EntityCollection<T> Convert(List<T> listToConvert) where T: class
Pop Catalin
+14  A: 

Read up on generic constraints in .NET. Specifically, you need a "where T : class" constraint, since EntityCollection cannot store value types (C# structs), but unconstrained T can include value types. You will also need to add a constraint to say that T must implement IEntityWithRelationships, again because EntityCollection demands it. This results in something such as:

public static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class, IEntityWithRelationships
DrPizza
+3  A: 

you need the generic constraint but also to declare your method as generic to allow this

  private static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class,IEntityWithRelationships
        {
            EntityCollection<T> collection = new EntityCollection<T>();

            // Want to loop through list and add items to entity
            // collection here.

            return collection;
        }
Pharabus