Using sealed string property in C #

I wrote a class in C #.

I came across this part of the sentence offered by the code refactor. And I didnt

get what exactly this tool had in mind when offering this suggestion / improvement.

Situation:

I used the 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.. } 

Code refactoring tool requested a warning: talking about access to a virtual member

To fix this, the tool automatically added a property

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

Can someone explain to me how adding a sealed property will influence and improve the situation.

Greetings

+4
source share
4 answers

You call the virtual member in the constructor. There is no gaurentee that your code will be launched if the class is inherited and this property is called. Sealing prevents this, since it cannot be overridden in child classes. This should not affect anything in this particular example.

+5
source

Since you set the virtual property in your constructor, the refactoring tool offers to seal the property so that the value cannot be changed in the inherited classes , it cannot be redefined in the inherited classes.

This does not improve performance and does not make sense in the script that you have (a Form ). So I just ignore him .

+1
source

This will help, since no derived classes can override it.

+1
source

Since you are dealing with Form , another option would be to simply 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 private properties, especially if you are accessing multiple virtual properties.

+1
source

Source: https://habr.com/ru/post/1345706/


All Articles