How to determine that a type T must have an ID field in a generic abstract class in C #

I am trying to create a general class that will allow me to save / delete Customers, Products, so that I can have all the base implementation in one place.

public class Product : ItemDataService<Product> { public int id {get; set;} } public class Customer : ItemDataService<Customer> { public int id {get; set;} } public abstract class ItemDataService<T, V> { public T Item { get; set; } public int Id { get; set; } public ItemDataService(T item) { Item = item; } public void SaveItem(T item) { if (Item.Id <= 0) { InsertItem(item); } } } 

How can I access the Id property of the customer class in the ItemDataService class ItemDataService that I can check Item.Id <= 0

+6
source share
1 answer

Define the ISomeInterface interface with the Id field, for example:

 public interface ISomeInterface { int Id { get; } } 

And then you can make your abstract class implement this interface, and also add a general constraint that requires T be an implementation of this interface, for example:

 public abstract class ItemDataService<T> : ISomeInterface where T : ISomeInterface { public int Id { get; set; } // ... public void SaveItem(T item) { if (Item.Id <= 0) // Id is accessible now.. { InsertItem(item); } } } 

EDIT

Actually, given your interesting inheritance tree, you don't need an interface at all. You can simply add a generic constraint that forces T be a child of ItemDataService<T> . It looks funny, but it works:

 public abstract class ItemDataService<T> where T : ItemDataService<T> { public int Id { get; set; } // ... public void SaveItem(T item) { if (Item.Id <= 0) // Id is accessible now.. { InsertItem(item); } } } 
+6
source

All Articles