How do you inherit StringBuilder in vb.net?

I want to add my own element to the StringBuilder class, but when I create it, IntelliSense does not call it.

public class myStringBuilder() Inherits System.Text.[StringBuilder should be here] .... end class 

Is it possible? thanks

+6
stringbuilder
source share
6 answers

StringBuilder NotInheritable (aka sealed in C #), so you cannot extract from it. You can try wrapping StringBuilder in your own class or using extension methods instead.

+16
source share

No, StringBuilder is a NotInheritable class. You can try to wrap a StringBuilder instance, but you cannot inherit it. You can also use extension methods if you are using .NET 3.5.

+3
source share

Here is what I came up with for those curious:

 Imports System.Runtime.CompilerServices Module sbExtension <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, _ ByVal arg0 As Object) oStr.AppendFormat("{0}{1}", String.Format(format, arg0), ControlChars.NewLine) End Sub <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, ByVal arg0 As Object, _ ByVal arg1 As Object) oStr.AppendFormat("{0}{1}", String.Format(format, arg0, arg1), ControlChars.NewLine) End Sub <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, _ ByVal arg0 As Object, _ ByVal arg1 As Object, _ ByVal arg2 As Object) oStr.AppendFormat("{0}{1}", String.Format(format, arg0, arg1, arg2), ControlChars.NewLine) End Sub <Extension()> _ Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _ ByVal format As String, _ ByVal ParamArray args() As Object) oStr.AppendFormat("{0}{1}", String.Format(format, args), ControlChars.NewLine) End Sub End Module 
+2
source share

StringBuilder is a sealed class ... therefore inheritance is not allowed.

+1
source share

StringBuilder is sealed. You cannot inherit it.

+1
source share

If you are using an earlier version of .Net, you can write basically the same StringBuilderExtensions class and then explicitly call the static method.

With .Net 3.5: myStringBuilder.MyExtensionMethod(etc...);

Pre-.Net 3.5: StringBuilderExtensions.MyExtensionMethod(myStringBuilder, etc...);

+1
source share

All Articles