views:

826

answers:

2

I'm trying to understand the generic interface as described in this

My example has an interface:

  public interface ITest<T> where T: class
  {
    T GetByID(int id);
  }

I have a class that implements the interface, using LINQ to enties in project Data, which contains the class myClass:

  public class Test<myClass> :  ITest<myClass> where myClass : class
  {
      Data.myEntities _db = new Data.myEntities();

      public myClass GetByID(int id)
      {
        var item = _db.myClass.First(m => m.ID == id);
        return item;
      }

  }

This produces an error saying "Cannot implicitly convert type 'Data.myClass' to 'myClass', but if I change public class Test<myClass> to public class Test<Data.myClass> I get the "Type parameter declaration must be an identifier not a type".

I'm obviously missing something, because I don't understand what's going on here. Can anyone explain it, or point to somewhere that might explain it better?

Thanks.

A: 

I suspect the problem is here:

 _db.myClass.First...

Is it possible you mean something like

_db.GetAll<myClass>().First...

I think you are confusing myClass as a type vs. myClass as a function _db implements?

n8wrl
No, that code works to return the myClass object with the specified ID using LINQ to Entites.
chris
So you have a property of Data.myEntities for each T you might have an interface for?
n8wrl
Because if you do then GetByID has to be a big switch statement to call the right one based on typeof(myClass).
n8wrl
+2  A: 

I think you want to just remove the generic parameter from the Test class.

... class Test : ITest<myClass> ...

as it stands now, the generic parameter name is shadowing the actual type name.

Brian
If I do that, the "where" gets an error stating "constraints are not allowed on non-generic declarations".
chris
Oh, the 'where' bit can be removed too.
Brian
@chirs, your missing the point. You should also remove the Type constraint. In this case, you where creating a Generic parameter named myClass.
bruno conde
@bruno: I'm pretty sure I'm missing something, which is why I asked the question :) But at this point, I don't even know what I'm missing - I can make the changes you suggest, and it works, but I don't understand the difference.
chris