1

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

Simon
  • 7,991
  • 21
  • 83
  • 163
  • Change the function in `testObject2` to `public override void testFunction()`. What you have right now is hiding (http://stackoverflow.com/questions/3838553/overriding-vs-method-hiding), not overriding. – Rob Aug 19 '15 at 05:27
  • Can you please have a look at my edit? – Simon Aug 19 '15 at 05:37
  • Sorry - I forgot to add - you need to add the keyword `virtual` to the `testObject` method as well. – Rob Aug 19 '15 at 05:38

3 Answers3

1
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.
    }
mybirthname
  • 17,949
  • 3
  • 31
  • 55
0

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()
    {

    }
}
Taher Rahgooy
  • 6,528
  • 3
  • 19
  • 30
0

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();
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88