4

I was writing a class in c#.

I stumbled upon the this piece of suggestion offered by a code refactor. And i didnt

get what exactly the tool meant when it offered this suggestion/improvement.

Situation :

I was using this.Text property to set the title in the constructor of my Form class.

Form()
{
   //some initialization code ...

   //...

   this.Text = "Non modal form";           //Suggestion offered here..
}

The code refactor tool prompted a warning : saying accessing virtual member

To correct this the tool automatically added a property

  public override sealed string Text
   {
        get { return base.Text; }
        set { base.Text = value; }
   } 

Can anyone explain me how, adding a sealed property will affect/improve the situation.

Cheers

4 답변


5

You are calling a virtual member in a constructor. There is no gaurentee that YOUR code will run if the class is inherited and that property is called. Making it sealed prevents this as it can not be overridden in child classes. This shouldn't affect anything in this specific example.



1

It will help since no derived classes can override it.


1

As you are dealing with a Form, another option would be to just move your initialization code to the Load event handler (as described by Jon Skeet here):

Load += delegate
{
    this.Text = "Non modal form";  
};

Using the Load event is much simpler than creating sealed properties, especially if you are accessing more than one virtual property.


1

Since you are setting a virtual property in your constructor, refactoring tool is suggesting to seal the property so that the value cannot be changed in the inherited classes it cannot be overriden in the inherited classes.

This does not improve performance, nor it makes sense in the scenario you have (a Form). So I would just ignore it.


  • This does not prevent inherited classes from changing the value of the property. It prevents inherited classes from changing the behavior of the property. - Adam Robinson
  • In addition, it's suggested here because it's bad practice to call virtual members from within a constructor, because you could cause code to execute on a class (an inherited class) that has not yet been constructed. - Adam Robinson
  • This cannot be overriden in the base classes, is this not baheviour??! - Aliostad
  • I'm not sure what you're asking. Your answer states that it's suggested "so that the value cannot be changed in the inherited classes". An inherited class can certainly change the value; it's a public property with a public setter. What an inherited class cannot do when it's sealed is override the behavior. - Adam Robinson
  • Yes, calling virtual method in constructor bad, but is this not what Windows Forms does in InitiliseComponents? So in this context (which is not exactly a nested hierarchy) I would ignore it. - Aliostad

Linked


Related

Latest