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

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.


0
Rajesh_Patil74
Asked:
Rajesh_Patil74
1 Solution
 
AlexFMCommented:
Replace new with override:

class Bbase
{
   public virtual void Method1()
   ...
}

class derived1 : Bbase
{
   public override void Method1()
   ...
}

class derived2 : Bbase
{
   public override void Method1()
   ...
}

In this case the following code calls right function:


 for ( i = 0; i < oArray.Count; i ++)
  {
     oBase = (Bbase)oArray[i];
     oBase.Method1();
  }
0
 
muzzy2003Commented:
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.
0
 
tstoeckigtCommented:
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
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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