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; }
}
}
Mark the property as virtual
within Base
class
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 thenew
modifier hides it.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With