The ToString Method

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. 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 ...

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

This gives you ...

... 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:

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

The result is:

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.

Format
mla apa chicago
Your Citation
Mabbutt, Dan. "The ToString Method." ThoughtCo, Jan. 29, 2020, thoughtco.com/the-tostring-method-3424262. Mabbutt, Dan. (2020, January 29). The ToString Method. Retrieved from https://www.thoughtco.com/the-tostring-method-3424262 Mabbutt, Dan. "The ToString Method." ThoughtCo. https://www.thoughtco.com/the-tostring-method-3424262 (accessed April 19, 2024).