Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance misunderstanding in C#

Tags:

c#

inheritance

I am trying to understand the way inheritance works in C#. Basically, I have a base class Base that has a simple function sayIt. The function makes use of a property "i" that is redefined in subclasses. Here, it is redefined as 1 from 0. When I run this program, I get "0" as output rather than "1" which is what I expected (because in python I would get 1). Can anyone explain why, and more importantly, whether this is a pattern that is supported in C#?

class Program
{
    static void Main(string[] args)
    {
        Derived d = new Derived();
        Console.WriteLine(d.sayIt());
        Console.ReadLine();
    }
}

class Base
{
    int _i = 0;
    public int i
    {
        get { return _i; }

    }

    public String sayIt()
    {
        return Convert.ToString(this.i);
    }
}

class Derived : Base
{
    int _i = 1;
    public new int i
    {
        get { return _i; }
    }
}
like image 242
guyrt Avatar asked Jan 07 '14 00:01

guyrt


2 Answers

  1. Mark the property as virtual within Base class

  2. Replace new with override next to the property within Derived class.

1. Is necessary because members are non-virtual in c# by default. and 2. is necessary, because using new would break the virtual resolving pass, what is not what your want.

There is nice article about new and override on MSDN: Knowing When to Use Override and New Keywords (C# Programming Guide).

The override modifier extends the base class method, and the new modifier hides it.

like image 77
MarcinJuraszek Avatar answered Oct 18 '22 17:10

MarcinJuraszek


In order to have a function that can be overriden by a derived type you need to make it virtual

public virtual int i
{
  get { return _i; }
}

Then in the derived type you can override the behavior with the override keyword

public override int i
{
  get { return _i; }
}
like image 36
JaredPar Avatar answered Oct 18 '22 17:10

JaredPar