Reputation: 9969
I have created this generic method
public IEnumerable<T> GetByID<T>(IEnumerable<T> source, int id) where T : IFields
{
return source.Where(x => x.id == id);
}
where the IFieds
interface is
public interface IFields
{
string code { get; set; }
int id { get; set; }
}
when i try to get the value, this obviously won't compile
DB.GetByID(Helper.Database.Table<Items>(), 1);
with the following compile error.
The type "Items" cannot be used as type parameter "T" in the generic type or method "DB.GetByID(System.Collections.Generic.IEnumerable, int)". There is no implicit reference conversion from "Items" to "IFields"
How can i fix that? Actually, i wish to use lambda expression "in an anonymous type".
Upvotes: 0
Views: 4027
Reputation: 391566
The obvious reason for this error message is that Items
doesn't implement IFields
.
In other words, your Items
type need to have this:
public class Items : IFields
^-----^
If you don't have this, then Items
is not a valid type for your GetByID<T>
method since it doesn't implement this interface.
This is true even if the Items
type just happens to have the right members. Unless you've explicitly stated that those members also implement the interface, by doing what I showed above, then that is not enough. So even if your Items
type have the id
property, you still have to state explicitly that the type implements the interface.
Upvotes: 3