I have a base class "Parent" like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Parent
{
private int parentVirtualInt = -1;
public virtual int VirtualProperty
{
get
{
return parentVirtualInt;
}
set
{
if(parentVirtualInt != value)
{
parentVirtualInt = value;
}
}
}
}
}
and a child class like this:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Child : Parent
{
public override int VirtualProperty
{
get
{
if(base.VirtualProperty > 0)
{
throw new ApplicationException("Dummy Ex");
}
return base.VirtualProperty;
}
set
{
if(base.VirtualProperty != value)
{
base.VirtualProperty = value;
}
}
}
}
}
Note that the getter in Child is calling the getter of Parent (or at least this is what I intend).
I now use the "Child" class by instantiating it, assigning a value (let's say 4) to its VirtualProperty and then reading the property again.
Child c = new Child();
c.VirtualProperty = 4;
Console.Out.WriteLine("Child.VirtualProperty: " + c.VirtualProperty);
When I run this, I obviously get an ApplicationException saying "Dummy Ex". But if I set a breakpoint on the line
if(base.VirtualProperty > 0)
in Child and check the value of base.VirtualProperty
(by hovering the mouse over it) before the exception can be thrown (I assume(d)), I already get the Exception. From this I convey that the statement base.VirtualProperty
in the "Child-Getter calls itself"; kind of.
What I would like to achieve is the same behavior I get when I change the definition of parentVirutalInt
(in Parent) to protected and use base.parentVirtualInt
in the Getter of Child instead of base.VirtualProperty
. And I don't yet see why this is not working. Can anybody shed some light on this? I feel that overridden properties behave differently than overridden methods?
By the way: I am doing something very similar with subclassing a class I do not have any control over (this is the main reason why my "workaround" is not an option).
Kind regards