• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 192
  • Last Modified:

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?


1 Solution
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


Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now