Convert Methods
The shared public members of the System.Convert class can be used to convert a base data type to another
base data type. (The fact that they are shared, of course, implies that you do have to instantiate a Convert
object to use them.)
You can use the Object Browser to have a look at them and discover what conversion methods are available
(there are quite a few).
For example, somewhat trivially, the Convert.ToBoolean method converts the string “False” to the bool value
false and displays a Message Box:
if (Convert.ToBoolean("False") == false){
MessageBox.Show("False");
}
else {
MessageBox.Show("True");
}
You’ll find a Convert class method for converting every base type to every other base type, and you’ll
probably find yourself using these methods quite a bit.
You should know that the Convert methods throw an exception (and don’t do any conversion) when meaningful
results cannot be obtained. For example, calling any of the methods that convert the reference type System.DateTime
to or from anything other than string always produces an exception (and no conversion takes place).
In addition, an overflow exception is thrown (and no conversion takes place) if you try to stuff too large a
value into a type that cannot store it.
|