Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the StringBuilder class sealed? [closed]

I'm wondering this, since I need to inherit from StringBuilder to implement a TextChanged event. I could always make a wrapper containing a private StringBuilder and implicit/explicit conversions, but this does not seem like a proper solution.

Luckily I can inherit from the object that is writing to the StringBuilder, so this is not really a problem for me, but I'm still curious as to why that class is sealed.

like image 236
KappaG3 Avatar asked Aug 02 '13 20:08

KappaG3


2 Answers

This is a bit difficult to answer. The upvoted answer has a problem, StringBuilder doesn't have any virtual methods. So there's nothing you could do to break the class or doing anything "extra" unsafe.

I think the likely reason is that the CLR has special knowledge of the class. That's a bit mundane for StringBuilder, compared to other .NET types it is intimate with, the pinvoke marshaller knows what the class looks like. You use it when you need to pass a string reference to unmanaged code, allowing it to write the string content. Necessary because that's not legal for String, it is immutable. The pinvoke marshaller knows how to set the internal members of StringBuilder correctly after the pinvoke call. But wouldn't know how to do that for your derived class. That slicing risk is not exactly worth the benefit of not sealing it. Particularly since it doesn't have virtual methods so you cannot override its behavior at all.

An extension method is otherwise a very reasonable workaround.

like image 148
Hans Passant Avatar answered Oct 31 '22 21:10

Hans Passant


StringBuilder is sealed because it assembles strings, e.g. there should never be a reason to inherit from it because any use should be limited in scope. StringBuilder is not a replacement for string and should never be used that way. The goal of the class was to have a way of easily handling any operations that required mutable strings without performance penalty. As such There is no way inheriting from StringBuilder would provide any utility and would create possible security issues as the class deals with mutable strings.

Take a look at the reference source it is not a simple class but a tightly focused utility. Furthermore it does things that are unsafe, and thus allowing inheritance would allow modification of unsafe code which could compromise security.

like image 7
Mgetz Avatar answered Oct 31 '22 21:10

Mgetz