EDIT to reflect the new information in your question: An ArrayList is a good way to proceed, but I wouldn't use generics in this case since it is going to cause a lot of headaches and code duplication. Instead, I would use reflection to find and invoke the correct overload at runtime. A snippet of code is worth one thousand words, so here's a simple console application to show this:
class ObjectA {
public int A { get; set; }
public ObjectA( int a ) {
this.A = a;
}
}
class ObjectB {
public int B { get; set; }
public ObjectB( int b ) {
this.B = b;
}
}
class ObjectC {
public int C { get; set; }
public ObjectC( int c ) {
this.C = c;
}
}
class DynamicOverloadResolution {
ArrayList items;
public DynamicOverloadResolution( ) {
items = new ArrayList( ) {
new ObjectA( 1 ), new ObjectB( 2 ), new ObjectC( 3 )
};
}
public void ProcessObjects( ) {
foreach ( object o in items )
processObject( o );
}
private void processObject( object o ) {
Type t = typeof( DynamicOverloadResolution );
IEnumerable<MethodInfo> processMethods = t.GetMethods( )
.Where( m => m.Name == "process" );
foreach(MethodInfo info in processMethods) {
if ( info.GetParameters( ).First( ).ParameterType == o.GetType( ) )
info.Invoke( this, new object[ ] { o } );
}
}
public void process( ObjectA a ) { Console.WriteLine( a.A ); }
public void process( ObjectB b ) { Console.WriteLine( b.B ); }
public void process( ObjectC c ) { Console.WriteLine( c.C ); }
}
class Program {
static void Main( string[ ] args ) {
var d = new DynamicOverloadResolution( );
d.ProcessObjects( );
}
}
And here's the output:
1
2
3
Old Answer:
You can simply make fruit an abstract class or an interface, have everything inherit from/implement it and keep a list of fruit:
interface IFruit {
public int c { get; set; }
}
class Apple : IFruit { }
class Peach : IFruit { }
class Lemon : IFruit { }
class Basket {
List<IFruit> fruitList = new List<IFruit>();
public void AddIFruit<T>(int c)
where T : IFruit, new {
var f = new T();
f.c = c;
fruitList.Add(f);
}
}
It is possible to know the exact type of the elements you get out from the list with the operator is:
var f = fruitList.First();
if(f is Apple) { }
else if(f is Peach) { }
else if(f is Lemon) { }
In alternative, you can use the as operator to convert from IFruit to one of its implementations (beware, the result will be null if the conversion is not possible, i.e. you used wrong types):
List<Fruit>a=Basket.GetFruits();
switch(a[0].c) {
case 0:
Lemon L = a[0] as Lemon;
}
But if you need to do this, then maybe you are approaching the problem from a wrong perspective.