[C#] Polymorphic oddity

Soldato
Joined
12 Apr 2004
Posts
11,788
Location
Somewhere
I've created a custom control that derives from TextBox, and overriden the Text property inherited from TextBox. The problem is that base.Text is not doing what it should do – it's just getting/setting my override of it. :confused:

Unless i'm misunderstanding polymorphism and the base keyword, this shouldn't be happening should it?

Edit: it works fine if I use the new keyword, but only when running; it causes odd behaviour in the designer (as it's getting/setting the TextBox.Text property instead).
 
Last edited:
Here's the code for the property:

Code:
public override string Text
{
    get
    {
        if (m_Empty)
        {
            return String.Empty;
        }
        else
        {
             return base.Text;
        }
    }
    set
    {
        base.Text = value;

        m_Empty = value == String.Empty;
        Display();
    }
}

And here's a screenshot illustrating the problem:

vs2005jl9.png
 
Last edited:
Well, the whole point in the base keyword is to provide access to otherwise overridden methods and properties as they are implemented in the base class, but it doesn't seem to be doing that. :confused:
 
growse said:
Well, that clears it up somewhat, but there's still a problem that the article can't explain.

The following code procuces two message boxes, both with identical text present in them (as opposed to the second being empty, as it should be):
Code:
if (m_Text == String.Empty)
{
    MessageBox.Show(base.Text);
    base.Text = String.Empty;
    MessageBox.Show(base.Text);
}

I've tried running it straight from the binary with no debugging process attached, but it still yields the same results.

Incidentally, the code for the Text property is now:
Code:
public override string Text
{
    get
    {
        return m_Text;
    }
    set
    {
        base.Text = m_Text = value;
        Display();
    }
}

Again, changing override to new solves the problem at runtime, but causes more problems in design view.
 
Last edited:
Nope, but it shouldn't make a difference should it?

I'll try it anyway though :)

edit: yup, still getting the same behaviour in VB.NET
 
Last edited:
geordiepaul said:
Looks ok to me! Rember it's an overridden property so if the base class uses this property it will use your version and not the base property unless you call base explicitly. In this instance you have already returned "test" so could have set the base property hence why the debugger is giving you "test".
How has it set the base property? :confused:
 
Back
Top Bottom