Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access the common methods from each objects by iterating through a list

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?

like image 926
GManika Avatar asked Feb 18 '23 04:02

GManika


2 Answers

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();
like image 55
juharr Avatar answered Feb 20 '23 16:02

juharr


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.

like image 39
Josep Avatar answered Feb 20 '23 18:02

Josep