C # generics error: Limitations for a parameter of type 'T' of a method ...?

Getting the following error:

Error 1 Restrictions for the parameter of type ' T ' of the method
' genericstuff.Models.MyClass.GetCount<T>(string) ' must comply with type restrictions
parameter ' T ' of the interface method ' genericstuff.IMyClass.GetCount<T>(string) '. Consider
using the explicit implementation of the interface instead.

Grade:

  public class MyClass : IMyClass { public int GetCount<T>(string filter) where T : class { NorthwindEntities db = new NorthwindEntities(); return db.CreateObjectSet<T>().Where(filter).Count(); } } 

Interface:

 public interface IMyClass { int GetCount<T>(string filter); } 
+7
source share
3 answers

You limit your general parameter T to a class in your implementation. You do not have this limitation for your interface.

You need to remove it from your class or add it to your interface in order to compile the code:

Since you call the CreateObjectSet<T>() method, which requires a class constraint , you need to add it to your interface.

 public interface IMyClass { int GetCount<T>(string filter) where T : class; } 
+18
source

You need to either apply the restriction to the interface method or remove it from the implementation.

You change the interface contract by changing the implementation restriction - this is not allowed.

 public interface IMyClass { int GetCount<T>(string filter) where T : class; } 
+3
source

You also need to limit your interface.

 public interface IMyClass { int GetCount<T>(string filter) where T : class; } 
+1
source

All Articles