Sei sulla pagina 1di 1

ToString and Parse

The simplest formatting mechanism is the ToString method. It gives meaningful output on all simple value types (bool, DateTime, DateTimeOffset, TimeSpan, Guid, and all the numeric types). For the reverse operation, each of these types defines a static Parse method. For example:
string s = true.ToString(); // s = "True" bool b = bool.Parse (s); // b = true

If the parsing fails, a FormatException is thrown. Many types also define a TryParse method, which returns false if the conversion fails, rather than throwing an exception:
int i; bool failure = int.TryParse ("qwerty", out i); bool success = int.TryParse ("123", out i);

If you anticipate an error, calling TryParse is faster and more elegant than calling Parse in an exception handling block

Potrebbero piacerti anche