2
Answers

Derived Classes

Photo of Dave

Dave

16y
2.3k
1

New to the site, and C#, and the site has been a great help.  I have been experimenting with the 'An Elegant C# Data Access Layer using the Template Pattern and Generics' article, hopefully someone can help me with this problem.

I have 3 objects:  ObjectA, ObjectB, ObjectC.  All 3 are derived from an object ParentObject.  Parent Object has a property 'ID'.

If the objects are stored in a Collection like: Collection<ObjectA>, Collection<ObjectB>, Collection<ObjectC>.

Is there any way that I can use Collection<ParentObject> as a parameter to a single function in order to read the 'Id' Property from either of the Collections. 

Answers (2)

0
Photo of Brandon Lewis
NA 603 116k 16y
Easy, just use a function with a generic type parameter and a generic constraint:

void MyFunction<T>(Collection<T> listOfObjs) where T : ParentClass
{
   // Process the list here
}


This will ensure that all objects in the list passed to MyFunction inherit from ParentClass, so they will all have the ID property.
Accepted
0
Photo of Dave
NA 3 0 16y
Thanks, Ill give this a try.