Hello I am having some difficulty with setting up a class , because of the types involved. Here is the Idea:
class A has a private arraylist which is supposed to be filled with instances of class B. So any instance of class A will have its on ArrayList of class B elements. class A has a function to add to its ArrayList a new instance of B. To be more specific, inside the A.Add, a new B is instantiated, and initialized, then added to the ArrayList. class B is a very simple class: It has one enum Type in it, and it should also contain a reference to an external object/class or whatever. Suppose there are classes * appleClass, peachClass , lemonClass * and classB is the fruit class, and class A is the fruitBasket. The everytime the main code sees a fruit, it should ask class A to add it in the basket. that means, A.add(thisfruit), but this fruit might be any of the fruitclasses. which in turn means that I need a generic signature to instantiate classB , and add it to A.arraylist. I don;t know if I make any sense but I will also try to give some code to explain my problem.
class Lemon
{
//....
}
class Apple
{
//....
}
class Peach
{
//....
}
class Fruit
{
public int color;
<T> fruit;///this should be the <T> type depending on the fruit class i am adding
public Fruit(T f, int c){fruit = f; color = c;}
}
class Basket
{
ArrayList FruitArray= new ArrayList();
public void AddFruit<T>(T f,int c )
{
fru = new Fruit(f,c);
FruitArray.Add(fru);
}
}
SomeHow I should use templates?? I know the code above is wrong, but I can't figure how is this best done.
Thank You
Alex
EDIT Thank You all for your answers. They all seem to point to using a base/abstract class Fruit, and derive specific fruits from it. I am sorry to tell you that my actuall project doesn't involve fruits, I just used them for simplicity. The actual project is in Unity and somr of the "fruits" are coming from Unity classes , some other "Fruits" are my own classes. this means that I can't declare parent class for the ones that come from Unity's namespace. I was more hopeing to be able to have a generic reference to the "fruit" , that would be a void pointer in good old C. I know C# is strongly typed, and won't allow most pointer-like uses, but there must me a way to pass an "unknown" reference-to-object to a class/function and use/resolve it later...