1. Technology

The ToString Method

More than you might expect

By

The ToString method is one of the fundamental methods in the root of the entire .NET Framework. That makes it available in every other object. (The other methods in the Object object are introduced in the Quick Tip: The Object Object.) But, since it's overridden in most objects, the implementation is often very different in different objects. And that makes a number of tricks with ToString possible.

Displaying the bits in a number

If you have a series of bits in, for example, a Char variable, this tip shows you how to display them as 1's and 0's (the binary equivalent).

Suppose you have ...

 Dim MyChar As Char
 'a character selected at random
 'just to get a series of eight bits
 MyChar = "$" 

The easiest way I know of is to use the ToString method of the Convert class. For example:

 Console.WriteLine(Convert.ToString(Convert.ToInt16(MyChar), 2)) 

This gives you ...

 100100 

... in the Output window.

There are 36 overridden methods of the ToString method in the Convert class alone.

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

In this case, the ToString method does a radix conversion based on the value of the second parameter which can be 2 (binary), 8 (octal), 10 (decimal) or 16 (hexadecimal).

Formatting Strings with the ToString method

Here's how to use ToString to format a date:

 Dim theDate As Date = #12/25/2005#
 TextBox1.Text = theDate.ToString("MMMM d, yyyy") 

And adding culture information is easy! Suppose you want to display the date from a structure in, say, Spain. Just add a CultureInfo object.

 Dim MyCulture As _
    New System.Globalization.CultureInfo("es-ES")
 CultureDateEcho.Text = _
    theDate.ToString("MMMM d, yyyy", MyCulture) 

The result is:

 diciembre 25, 2005 

The culture code is a property of the MyCulture object. The CultureInfo object is an example of a provider. The constant "es-ES" isn't being passed as a parameter; an instance of the CultureInfo object is. Search the VB.NET Help system for CultureInfo to see the list of supported cultures.

See More About
  1. About.com
  2. Technology
  3. Visual Basic
  4. Quick Tips
  5. Using the ToString Method in a Visual Basic .NET

©2014 About.com. All rights reserved.