CSharp - ToString and Parse

Introduction

ToString method gives meaningful output on all simple value types, such as 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.

TryParse method returns false if the conversion fails, rather than throwing an exception:

int i;
bool failure = int.TryParse ("book2s.com", out i);
bool success = int.TryParse ("123", out i);

Parse and TryParse methods on DateTime(Offset) and the numeric types respect local culture settings.

You can change this by specifying a CultureInfo object.

The following code uses invariant culture during parsing:

double x = double.Parse ("1.234", CultureInfo.InvariantCulture);

The same applies when calling ToString():

string x = 1.234.ToString (CultureInfo.InvariantCulture);