0

I have a List of two different objects i.e.

List<Customer> Customers;
List<Retailer> Retailers;

I have a method which if i pass in the List with the appropriate type separately everything works.

I thought to try Generics to see if i can have one method to do two tasks i.e. Pass in the type of List and it would iterate through the list and get the record and take whatever action necessary.

        private T AddRecord<T>(List<T> ListofRecords)
        {
            foreach (T rec in ListofRecords.Records)
            {
                Object ob = GetRecord(rec.Id);
            }
        }

The issue i'm coming across is that rec (the variable for the foreach loop) doesnt know what type it is so i cant get to the ID property.

How should i be doing this?

Computer
  • 2,149
  • 7
  • 34
  • 71

2 Answers2

1

Both Customer and Retail must share the same base class ( or implement the same interface ) having the property Id. Then in your function:

 private T AddRecord<T>(List<T> ListofRecords) where T:YourBaseClass
        {
            foreach (T rec in ListofRecords)
            {
                Object ob = GetRecord(rec.Id);
            }
        }

with where T: you sentence that T must derive ( or implement ) your base class (interface ) so compiler can be aware of the existence of the Id property.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
1

If you have a common ancestor, You can limit T to that using the where keyword -

interface IHasId
{
    int Id { get; }
}

private T AddRecord<T>(List<T> listofRecords) where T: IHasId
{
    foreach (var rec in listofRecords)
    {
       var theId = rec.Id;
    }
    ...
}
Sam
  • 1,208
  • 1
  • 9
  • 16