Question

I want to add my own member to the StringBuilder class, but when I go to create it IntelliSense doesn't bring it up.

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

Is it even possible? thanks

Was it helpful?

Solution

StringBuilder is NotInheritable (aka sealed in C#) so you cannot derive from it. You could try wrapping StringBuilder in your own class or consider using extension methods instead.

OTHER TIPS

No, StringBuilder is a NotInheritable class. You could try wrapping a StringBuilder instance, but can't inherit from it. You can also use extension methods, if you're using .NET 3.5.

This is what I came up with, for those who are 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

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

StringBuilder is sealed. You cannot inherit from it.

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top