Using 'new' to override non-virtual methods

P

Paul E Collins

I am writing a class that inherits from TextBox. My class,
UndoTextBox, extends the standard control by enabling multi-level undo
and redo operations.

Annoyingly, some of the affected properties and methods (such as
CanUndo and Clear) are not virtual and therefore cannot be overridden.
I have hacked around this by declaring 'new' methods, e.g.

public new bool CanUndo
{
get { return m_undoStack.CanUndo; }
}

Since "a constant, field, property, or type introduced in a class or
struct hides all base class members with the same name", I assume that
the correct CanUndo will be called even if, say, the object in
question has been cast to TextBoxBase.

However, this still feels like a (necessary) hack. Are there any other
repercussions I should take into account when using 'new' like this?

P.
 
R

Richard A. Lowe

Inline

--
C#, .NET and Complex Adaptive Systems:
http://blogs.geekdojo.net/Richard
Paul E Collins said:
I am writing a class that inherits from TextBox. My class,
UndoTextBox, extends the standard control by enabling multi-level undo
and redo operations.

Annoyingly, some of the affected properties and methods (such as
CanUndo and Clear) are not virtual and therefore cannot be overridden.
I have hacked around this by declaring 'new' methods, e.g.

public new bool CanUndo
{
get { return m_undoStack.CanUndo; }
}

Since "a constant, field, property, or type introduced in a class or
struct hides all base class members with the same name", I assume that
the correct CanUndo will be called even if, say, the object in
question has been cast to TextBoxBase.

No, if by the "correct" CanUndo you mean your "new" CanUndo - it won't be
called if the reference is cast to TextBoxBase. That is the difference
between overriding and hiding via 'new'. Your CanUndo member is truly
"hidden" from TextBoxBase - the base class can never access it (unless you
were able to go back and make TextBoxBase aware of its derived type - not
usually a good idea!). How you get around this limitation really depends
on the context of the situation, but I'm afraid there's no way to directly
override non-virtual members.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top