Need help with C # generics

I had trouble writing a class that uses generics, because this is the first time I had to create a class that uses generics.

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

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

Here is the code I'm 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; } 

He complains about the assembly EntityCollection = new line of EntityCollection () code.

If anyone can help me with this error or explain to me why I get it, I would really appreciate it. Thanks.

+4
source share
4 answers

Read the general limitations in .NET. In particular, you need a "where T: class" constraint, since EntityCollection cannot store value types (C # structs), but unlimited T can include value types. You will also need to add a constraint to say that T must implement IEntityWithRelationships, again because it requires an EntityCollection. This leads to something like:

 public static EntityCollection<T> Convert<T>(List<T> listToConvert) where T : class, IEntityWithRelationships 
+14
source

You must restrict the type parameter T to a reference type:

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

You will probably get this error, because the EntityCollection constructor requires that T be a class, not a structure. You need to add the where T:class constraint to your method.

+3
source

you need a general constraint, but also 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; } 
+3
source

All Articles