ToString method gives meaningful output on all simple value types, bool, DateTime, DateTimeOffset, TimeSpan, Guid, and int, uint, long, float and double.
For the reverse operation, each of these types defines a static Parse method.
In the following we first convert a bool type literal true to string then convert the string back to bool with bool.Parse.
If the parsing fails, a FormatException is thrown.
using System;
using System.Text;
using System.Globalization;
class Sample
{
public static void Main()
{
string s = true.ToString();
Console.WriteLine(s);
bool b = bool.Parse(s);
Console.WriteLine(b);
}
}
The output:
True
True
Many types also define a TryParse method, which returns false if the conversion fails, rather than throwing an exception:
using System;
using System.Text;
using System.Globalization;
class Sample
{
public static void Main()
{
int i;
bool failure = int.TryParse("abc", out i);
Console.WriteLine(failure);
bool success = int.TryParse("123", out i);
Console.WriteLine(success);
}
}
The output:
False
True