Simon
Simon

Reputation: 8357

How do I call a function in a polymorphic object list?

In C#, if I have an object that is inherited from another object, and I have a list of the inherited object, how can I call a function in the base class?

Here is an example:

class testObject
{
    public void testFunction()
    {

    }
}

class testObject2 : testObject
{
    public void testFunction()
    {

    }
}

Here is the list:

List<testObject> testObjects

If I add some testObject2 objects to the list, how can I call the testFunction function for each testObject2 object? If I try and call testFunction for each object, the testFunction in the testObject is called.

EDIT

When adding the override code to the testFunction in testObject2, I am getting this error:

cannot override inherited member because it is not marked virtual, abstract, or override

Upvotes: 1

Views: 295

Answers (3)

mybirthname
mybirthname

Reputation: 18127

class testObject
{
    public virtual void testFunction()
    {

    }
}

class testObject2 : testObject
{
    public override void testFunction()
    {

    }
}

You need to add virtual to the method in testObject class and override it in the testObject2. If you want to add a little logic to already existing logic you can do it like this:

    public override void testFunction()
    {
         //it is calling the method in base
         base.testFunction();

        //here you can add more logic if you want.
    }

If you want totally separate method in which you do something else you just

    public override void testFunction()
    {
        //write another logic.
    }

Upvotes: 1

sujith karivelil
sujith karivelil

Reputation: 29006

Class Definition:

class  testObject
    {
        public string s;
        public virtual void testFunction()
        {
            string b = s;
        }
    }

    class testObject2 : testObject
    {
        public string m;
        public override void testFunction()
        {
            string x = m;

        }
    }

Function call:

  List<testObject> testObjects = new List<testObject>();
  testObjects.Add(new testObject2() { m = "a" });
  testObjects[0].testFunction();

Upvotes: 0

Taher  Rahgooy
Taher Rahgooy

Reputation: 6696

To enable polymorphic funtions you must declare the function as virtual, or abstract and then override them in child classes

class testObject
{
    public virtual void testFunction()
    {

    }
}

class testObject2 : testObject
{
    public override void testFunction()
    {

    }
}

Upvotes: 0

Related Questions