I have multiple types of object instances that inherit from a common interface.
I would like to access the common methods from each objects by iterating through a list or arraylist or collections. how do I do that?
{
interface ICommon
{
string getName();
}
class Animal : ICommon
{
public string getName()
{
return myName;
}
}
class Students : ICommon
{
public string getName()
{
return myName;
}
}
class School : ICommon
{
public string getName()
{
return myName;
}
}
}
When I add the animal, student, and School in an object[], and try to access
in a loop like
for (loop)
{
object[n].getName // getName is not possible here.
//This is what I would like to have.
or
a = object[n];
a.getName // this is also not working.
}
is it possible to access the common method of different types in from a list or collections?
You need to either cast the object to
ICommonOr perferably you should use an array of
ICommonOr you might want to consider using a
List<ICommon>