Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual member call in constructor [duplicate]

In my application I am running the same winform in different contexts to control visibility of buttons, enabeling of text fields and the winform header text. The way I decided to do this is simply by passing a string to the form constructor and check it with a couple of if statements that in turn contain the desired winform tweaks.

if (formContext == "add")
{
    Text = "Add member";
}
if (formContext == "edit")
{
    Text = "Change role";
    userTextBox.Enabled = false;
    searchButton.Visible = false;
}

This works fine, however the "Text" keywords get a blue squigly line added by ReSharper with the following message: Viritual member call in constructor. Is this a potential problem or just some sort of overly enthusiastic ReSharper message.

Any clarification or suggestions for improvement of my implementation would be much appreciated.

like image 707
Sakkle Avatar asked Jan 19 '09 12:01

Sakkle


2 Answers

A virtual member call in the base class ctor could cause some logic to run in the subclass before the subclass' ctor is called (and thus before the object gets a chance to initialize itself to a consistent state).

It's just a nice reminder so you know you are doing something that could potentially cause some nasty unexpected behavior.

like image 146
mookid8000 Avatar answered Oct 15 '22 16:10

mookid8000


In addition to the existing answers, for forms you could add a Load event handler:

Load += delegate
{
    if (formContext == "add")
    {
        Text = "Add member";
    }
    if (formContext == "edit")
    {
        Text = "Change role";
        userTextBox.Enabled = false;
        searchkButton.Visible = false;
    }
};
like image 31
Jon Skeet Avatar answered Oct 15 '22 15:10

Jon Skeet