Link to home
Start Free TrialLog in
Avatar of Rajesh_Patil74
Rajesh_Patil74

asked on

Collection of Classes --

Hi

I have a two classes which are inherited from one class. I want to make collection of all derived classes in one list.
And when i enumrate thro that collection i should able to call correct method of that class.

For ex --

class Bbase
{
   // public member, method ....
   public virtual void Method1()
    {
    }
}

class derived1 : Bbase
{
   public new void Method1()
   {
   }
   public void Method1_1()
   {
   }
}


class derived1 : Bbase
{
   public new void Method1()
   {
   }
   public void Method2_1()
   {
   }
}



// Main function is something like that ...
Main()
{
   ArrayList  oArray;
   derived1  ob1, ob2, ob3;
   derived2   o1, o2;
   int i;

   Bbase oBase;
   oArray = new ArrayList();
   
  // Added all these object in collection
   ob1 = new derived1();
   ob2 = new derived1();
   ob3 = new derived1();
   o1 = new derived2();
   o2 = new derived2();
   oArray.Add(ob1);
   oArray.Add(ob2);
   oArray.Add(ob3);
   oArray.Add(o1);
   oArray.Add(o2);
 

  // Interate thro array.
  for ( i = 0; i < oArray.Count; i ++)
  {
     oBase = (Bbase)oArray[i];
     oBase.Method1();  // Always calls Base - method1.

    // To make it correct

   if (oArray[i].GetType().Name == "derived1")
        oDerived1 = (dervied1)oArray[i];
        oDervied1.Method1();
   else if (oArray[i].GetType().Name == "derived2")
        oDerived2 = (dervied2)oArray[i];
        oDervied2.Method1();
   
  }
}

In above code , i type cast the array object. I want to do that without typecasting .... Is it possible ??

Regards & Thanks.


ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of muzzy2003
muzzy2003

If you specify override and not new for the Method1 declarations in the inheriting objects, then oBase.Method1() should call the method you want it to.
For enumerating through an [collection|list|array] you should use the foreach keyword:

foreach(Bbase oBase in oArray)
  oBase.Method1();

This version looks much cleaner.

Your classes should also use the keyword override as AlexFM and muzzy2003 already mentioned.

Ciao
Timo