Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of the sealed string property in c#

Tags:

c#

.net-2.0

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

like image 930
this-Me Avatar asked Feb 24 '23 16:02

this-Me


1 Answers

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.

like image 183
Chris Kooken Avatar answered Feb 27 '23 05:02

Chris Kooken