3

I am trying to build a generic method and four classes that implement IDetail. Each class has a collection of a classes that implement ITaxes. I want to build a generic method that will allow me to access the collection of each class.

Something like this:

public void UpdateCollection<T,I>(T Detail,Taxes TaxesList ) where T:IDetail where I:Itaxes
{
   foreach( Taxes  tax in TaxesList)
   {
       Detail.I.Add(tax);
   } 
} 

I want to access the property of type I in type T. How can I do that? It is possible? Do I need to write one method for each class?

9
  • 2
    You can use reflection. Commented Oct 14, 2013 at 16:09
  • 1
    What do you mean by "the property of type I"? There could be multiple such properties, or none... you could use reflection to find all such properties, but it would be a very odd approach IMO. Commented Oct 14, 2013 at 16:09
  • 2
    Does IDetail implement an I property? Commented Oct 14, 2013 at 16:14
  • 2
    This is the usual situation where a bad data model leads to all sorts of convoluted stuff Commented Oct 14, 2013 at 16:14
  • 1
    Could you explain the purpose of using generics here? Would polymorphism and normal use of interfaces be sufficient? i.e. if all IDetails have an Itaxes property - defined in the interface - then generics might not be the way to go. Commented Oct 14, 2013 at 17:05

2 Answers 2

6

Ideally you'd modify your IDetail interface to include the list of ITaxes objects as a part of that interface. You could use explicit interface implementation if you want the named property that is exposed publicly to have a different name for each detail.

If that isn't possible, or doesn't make sense for other reasons, then your best bet is probably to have this method accept a Func<T, I> parameter to this method. The user can then provide a method to allow you to extract the required list from each T object:

public void UpdateCollection<T, I>(T Detail, Taxes TaxesList, Func<T, I> taxSelector)
    where T : IDetail
    where I : Itaxes
{
    I taxList = taxSelector(Detail);
    foreach (Taxes tax in TaxesList)
    {
        taxList.Add(tax);
    }
}

The caller than can use a lambda to define the appropriate property for that object.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't have much experience with Func, please could you give me some ligth about the use of Func<T,I> taxSelector tks a lot for your help.
It's a delegate. It represents a function that accepts a single parameter of type T and returns an object of type I.
@Srvy, very very tks for your help
0

Create a third interface which exposes the commonality of what you seek. In partial classes (if generated) subscribe to the interface and then within the generic method accept only that interface and process accordingly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.