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.
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.