Why is the StringBuilder class sealed?

I am interested in this since I need to inherit from StringBuilder to implement the TextChanged event. I could always make a wrapper containing private StringBuilder and implicit / explicit conversions, but this does not seem to be the right solution.

Fortunately, I can inherit from the object that StringBuilder writes, so this is not a problem for me, but I'm still wondering why this class is sealed.

+6
source share
2 answers

It is a little difficult to answer. The above answer has a problem, StringBuilder has no virtual methods. Thus, you can’t do anything to break the class or make something "unnecessary" unsafe.

I think the probable reason is that the CLR has a special knowledge of this class. This is a bit commonplace for StringBuilder, compared to other .NET types with which it is intimate, pinvoke marker knows what the class looks like. You use it when you need to pass a string reference to unmanaged code, allowing it to write string content. Necessary, because it is not legal for String, it is immutable. The pinvoke router knows how to properly set the internal elements of a StringBuilder after calling pinvoke. But I don’t know how to do this for your derived class. This risk of slicing is not entirely worth noting to seal it. In particular, since it does not have virtual methods, therefore, you cannot completely override its behavior.

An extension method otherwise is a very reasonable solution.

+12
source

StringBuilder sealed as it collects strings, for example. there should never be a reason to inherit it, because any use should be limited in scope. StringBuilder not a replacement for string and should never be used that way. The purpose of this class was to be able to easily handle any operations that require mutable strings without sacrificing performance. Thus, no way to inherit from StringBuilder will provide any utility and will create possible security problems, since the class deals with mutable strings.

Take a look at the reference source , this is not a simple class, but a dense, focused utility. In addition, it does things that are unsafe , and thus allowing inheritance will allow you to modify insecure code that could compromise security.

+6
source

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


All Articles