Using strings in VB.NET
Visual Basic .NET has a wide range of types defined, by default, to use in your applications. It offers the traditional types for handling numbers and strings, and other types are provided by .NET to represent objects and collections.
Understanding the types in Visual Basic .NET and how they are used is important in designing objects that best use what .NET provides. It's also important to understand that all data types used in .NET languages are common between the different .NET programming languages so that objects can be shared among them.
This tip is excerpted from InformIT. It is a portion of a chapter of Sams Teach Yourself Object-Oriented Programming with Visual Basic.NET in 21 Days, by Richard Simon.
The String data type is actually implemented as a class, not as a structure like the numeric data types. It also has a variable size depending on the implementing platform. For example, some platforms implement a String with 2 bytes per character, whereas others implement it as a single byte per character.
The major difference between using String in previous versions of Visual Basic and in Visual Basic .NET is that the String can't be declared with a fixed length. When a value is assigned to the String, the value's length determines the String's length.
Because strings are implemented by the .NET Framework, they also have different internal characteristics than before. An instance of a String can't be modified after it's created; even though it appears you are modifying the value, in actuality, a new instance of a String is created containing the modification. For example, consider the following code segment:
Dim SL As String = "Books"
SL = SL.Remove(4,1)
SL = SL + "s"
The first statement declares a String variable and assigns a value of "Books". This statement, in turn, allocates the appropriate memory in the String to store the value. The second statement uses the Remove() method to remove the s from the end of the value. It does so by creating a new instance of a String with the modified value and returning a reference to which the SL variable is set. The third statement appends the s back to the end of the value stored in SL. This statement has the same effect as calling a method within String because it also returns a reference to a new instance of a String that contains the modified value.
If you want to actually modify the value within a String, you can use the StringBuilder class. This class allows you to modify a string by inserting and removing characters.
To read the entire article from which this tip is excerpted, click over to InformIT. You have to register there, but the registration is free.
To learn more about Sams Teach Yourself Object-Oriented Programming with Visual Basic.NET in 21 Days, or to buy this book, click here.
This was first published in April 2002