Adding Different Item types to a C# Collection

I have a class in C# that inherits the Collectionbase with appropriate routines (code snippet below,

public class MyClass : System.Collections.CollectionBase
  //Add a Standard Segment Object
  public void Add(Segment xSegment)

  //Add a Loop Object
  public void Add(Loop xLoop)
 public Loop LoopItem(int Index)

 public Segment Item(int Index)

I have encountered an instance however, where I think it will be most efficient if I can have a collection class that can hold two different type of Objects.  I was able to override the add routine easily enough.  But as you can see I cannot override the "Get" item routine.  I have to have LoopItem and Item routines which causes problems later on.

Any ideas?


Who is Participating?
return an object

public object Item(int Index)

Then after you have it returned you can see what type of object it is and use it accordingly.
mandalorian4Author Commented:

Thank you! It was right in front of me!

Hi Mandalorian

The problem you're experiencing is the following.....

every method in C# has a method name, its parameters and the return type.

Unfortunately, if the name and the parameters are the same, the compiler doesn't know which method the programmer is calling so as to know the type of the object to return..... it wouldn't know until runtime.

Thats why methods called the same cannot differ only in the return type.

Therefore as SRigney you should return an object and evaluate after which type of object you're receiving.

Hope this helps

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.