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.
-
3Could you describe in more detail what are you trying to do? Do you already know which items are `Savings` and which `Checking`? Can't you use a virtual method that would be implemented differently in each type? – svick Sep 11 '12 at 23:52
-
1If the accounts are different, and you must use that difference in your code (i.e. use elements of type `Checking` differently from elements of type `Savings`) then don't put them in the same array. – Sergey Kalinichenko Sep 12 '12 at 00:07
3 Answers
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
.

- 868,454
- 176
- 1,908
- 1,964
-
Thank you, I tried casting it earlier, but didn't put the outer parentheses, only around the cast. Thanks! – Kefkamaydie Sep 11 '12 at 23:52
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.

- 14,391
- 32
- 45
-
I am a student, and the professor called for the different derived objects to be placed in the same array. Only reason it was done that way! – Kefkamaydie Sep 12 '12 at 01:44
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();
}

- 45,951
- 44
- 147
- 243