Note that there are some explanatory texts on larger screens.

plurals
  1. POCalling "Base-Getter" in Overriding Getter of Property
    text
    copied!<p>I have a base class "Parent" like this:</p> <pre><code>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; } } } } } </code></pre> <p>and a child class like this:</p> <pre><code>using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Child : Parent { public override int VirtualProperty { get { if(base.VirtualProperty &gt; 0) { throw new ApplicationException("Dummy Ex"); } return base.VirtualProperty; } set { if(base.VirtualProperty != value) { base.VirtualProperty = value; } } } } } </code></pre> <p>Note that the getter in Child is calling the getter of Parent (or at least this is what I intend).</p> <p>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.</p> <pre><code>Child c = new Child(); c.VirtualProperty = 4; Console.Out.WriteLine("Child.VirtualProperty: " + c.VirtualProperty); </code></pre> <p>When I run this, I obviously get an ApplicationException saying "Dummy Ex". <strong>But</strong> if I set a breakpoint on the line</p> <pre><code>if(base.VirtualProperty &gt; 0) </code></pre> <p>in Child and check the value of <code>base.VirtualProperty</code> (by hovering the mouse over it) <strong>before the exception can be thrown</strong> (I assume(d)), I already get the Exception. From this I convey that the statement <code>base.VirtualProperty</code> in the "Child-Getter calls itself"; kind of.</p> <p>What I would like to achieve is the same behavior I get when I change the definition of <code>parentVirutalInt</code> (in Parent) to protected and use <code>base.parentVirtualInt</code> in the Getter of Child instead of <code>base.VirtualProperty</code>. 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?</p> <p>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).</p> <p>Kind regards</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload