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 ICommon
var a = (ICommon)object[n];
a.getName();
Or perferably you should use an array of ICommon
ICommon[] commonArray = new ICommon[5];
...
commonArray[0] = new Animal();
...
commonArray[0].getName();
Or you might want to consider using a List<ICommon>
List<ICommon> commonList = new List<ICommon>();
...
commonList.Add(new Animal());
...
commonList[0].getName();
Just use an "ICommon" array instead of using an "Object" array, otherwise when you retrieve the items of the "Object" array you will have to cast them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With