Question

So I have an array of type Account, which is made up of Savings and Checking, which are derived from Account. Is it possible to get these to call their methods? Compiler only makes methods from base class visible, and I cannot get access to the methods in the derived classes. Banging my head on the wall here.

Was it helpful?

Solution

You need to cast the element in the array to the derived class:

((Checking)someArray[42]).Whatever();

If the instance is not actually of that type, this will throw an InvalidCastException.

OTHER TIPS

Although you can use casting, since you don't know the exact type of array elements, this would result in bunch of exceptions and a rather ugly code to handle them.

You can use something like:

Saving s = array[i] as Saving;
if(s != null)
{
   s.SomeSavingMethod();
}
else
{
   Checking c = array[i] as Checking;
   if(c != null)
      c.SomeCheckingMethod();
}

However, guessing the type and calling the method accordingly, is usually considered a bad design. This sounds like case for virtual methods, or these things shouldn't be in the same array in the first place.

There is basically two methods with which you can accomplish the functionality you appear to be looking for.

The first and arguably best (for the situation you describe) being declaring a common interface that all those classes implement.

public interface IWorker
{
    void DoWork();
}

public class A : IWorker
{
    public void DoWork()
    {
        // TODO: Implement this method
        throw new NotImplementedException();
    }
}

public class B : IWorker
{
    public void DoWork()
    {
        // TODO: Implement this method
        throw new NotImplementedException();
    }
}

The second being detecting the type and invoking the method if it supports it. Along these lines. This is where the AS operator is very handy because it will only return a non null value if the cast succeeds.

List<object> workers = new List<object>() { new A(), new B() };
foreach (object itm in workers)
{
    ClassThatSupportsDoWork obj = itm as ClassThatSupportsDoWork;
    if (obj != null)
        obj.DoWork();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top