Access to common methods from each object by iterating through a list

I have several types of object instances that inherit from a common interface. I would like to access common methods from each object, iterating through a list or arraylist or collection. how to do it?

{ 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 an animal, student and school to object [] and try to access in type loop

 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. } 

Can I access a common method of different types from a list or collections?

+4
source share
2 answers

You need to either move the object in ICommon

 var a = (ICommon)object[n]; a.getName(); 

Or maybe you should use an ICommon array

 ICommon[] commonArray = new ICommon[5]; ... commonArray[0] = new Animal(); ... commonArray[0].getName(); 

Or you might want to use List<ICommon>

 List<ICommon> commonList = new List<ICommon>(); ... commonList.Add(new Animal()); ... commonList[0].getName(); 
+6
source

Just use the ICommon array instead of using the Object array; otherwise, when you retrieve the elements of the Object array, you will have to distinguish them.

+2
source

All Articles