Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Access the Properties of a Generic Object

I have a method that counts the number of Contacts each Supplier, Customer and Manufacturer has (this is a scenario to try make explaining easier!)

The models are all created by Linq to SQL classes. Each Supplier, Customer and Manufacturer may have one or more Contacts

public int CountContacts<TModel>(TModel entity) where TModel : class
{
    return entity.Contacts.Count();
}

The above of course doesnt work, because the 'entity' is generic and doesnt know whether it has the property 'Contacts'. Can someone help with how to achieve this?

like image 991
Jimbo Avatar asked May 21 '10 14:05

Jimbo


2 Answers

An easy way would be to attach an interface to the classes being implemented in the generic.

public int CountContacts<TModel>(TModel entity) where TModel : IContacts


interface IContacts
{
   IList<Contact> Contacts {get;} //list,Ilist,ienumerable
}
like image 113
kemiller2002 Avatar answered Nov 02 '22 18:11

kemiller2002


One way to impose a contract where Suppliers, Customers and Manufactors must contain a Contacts property is with interfaces. Make each entity implement one interface that contains the Contacts property:

interface IContactable
{
   IEnumerable<Contact> Contacts {get;}
}


public int CountContacts<TModel>(TModel entity) where TModel : class, IContactable
{
    return entity.Contacts.Count();
}
like image 28
bruno conde Avatar answered Nov 02 '22 18:11

bruno conde