Brian DiCasa
Brian DiCasa

Reputation: 9487

Need help with C# generics

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.

Upvotes: 4

Views: 844

Answers (4)

DrPizza
DrPizza

Reputation: 18360

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

Upvotes: 14

Pharabus
Pharabus

Reputation: 6062

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

Upvotes: 3

Pop Catalin
Pop Catalin

Reputation: 62980

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

public static EntityCollection<T> Convert(List<T> listToConvert) where T: class

Upvotes: 5

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68737

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.

Upvotes: 3

Related Questions