What are the dangers of making a method virtual?
Asked Answered
M

3

8

I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.

I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?

Merritt answered 26/9, 2008 at 1:29 Comment(2)
I've never used Rhino, so I'm curious as to why it requires this. Anyone care to explain?Boar
I'm assuming Rhino overrides the methods in order to mock the interface by using the same type but mock behavior.Sculpsit
E
10

Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider:

class Base {
    public Base() {
       InitializeComponent();
    }
    protected virtual void InitializeComponent() {
        ...
    }
}

class Derived : Base {
    private Button button1;
    public Derived() : base() {
        button1 = new Button();
    }
    protected override void InitializeComponent() {
        button1.Text = "I'm gonna throw a null reference exception"
    }
}

The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run.

Eichman answered 26/9, 2008 at 1:51 Comment(0)
S
4
  • If you have users that override your virtual methods you can't seal them again without breaking code.
  • Any virtual methods you call from the constructor may fall down to derived implementations and if they don't call the base method and the constructor depends on it, the object may be in an invalid state
Sculpsit answered 26/9, 2008 at 1:33 Comment(0)
L
2

Ayende has a nice treatment of how virtual methods work:

http://ayende.com/Blog/archive/2007/01/05/HowVirtualMethodsWork.aspx

Labuan answered 26/9, 2008 at 1:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.