DotNet Example: Using System.Text.StringBuilder


The script below shows an interactive window session in which the .NET type System.Text.StringBuilder is mapped into the Xbasic type system.

This example is more demonstrative than useful. Although StringBuilder is an efficient way to build large strings in .NET applications, calling into .NET from Xbasic is a fairly expensive operation and using StringBuilder this way would come at a cost.

We do not have to specify an assembly for System.Text.StringBuilder when we register the class because it is part of an assembly that has already been loaded into memory. In fact, we do not really have to go to the trouble of registering the StringBuilder class at all, as it is pre-loaded along with most of the core .NET System namespace when Alpha Anywhere starts up.

' Register StringBuilder as MyNS::MyS
' (for demonstration purposes)
dim sv as DotNet::Services
?sv.registerclass("MyNS", "MyS", "System.Text.StringBuilder")
= .T.
dim s as MyNS::MyS
'NOTE: All of the above could actually be replaced by:
'dim s as System::Text::StringBuilder
' Read the Capacity property
= 16
' Set the Capacity property and read it back to be sure
' (not required in practice except in tight memory situations)
s.capacity = 44
= 44
' Add a string value
' Ensure capacity compares the value you send with the current capacity.
' If you need more space, the capacity will be changed.
' The resulting capacity is returned.
' (not required in practice except in tight memory situations)
= 66
' Remove two characters starting with the second one.
' .NET functions are zero based.
' Note: StringBuilder is an object. 
' To get the string value, call the function ToString()
= "Hlo"
' Insert the value back into the string and check the new value
s.insert(1, "el")
= "Hello"
' Add the string ' Bob' to the string
' Replace 'Bob' with 'Fred'
' Check the value
s.append(" Bob")
s.Replace("Bob", "Fred")
= "Hello Fred"

See Also