User Tools

Site Tools


Parsing and Casting in C#

Use the Parse method if you are certain the parsing will succeed. Otherwise, use TryParse.

The difference between Parse/TryParse and Convert is that Convert allows null values. It doesn't throw an ArgumentNullException; instead, it returns the default value for the supplied type. Also, Parse takes only a string as its input, while Convert accepts other types.


Console.WriteLine(Boolean.TrueString);    // True
Console.WriteLine(Boolean.FalseString);   // False
Console.WriteLine(Boolean.Parse("true")); // True
Console.WriteLine(Boolean.Parse("yes"));  // FormatException
Console.WriteLine(Boolean.Parse(null));   // ArgumentNullException


using System.Globalization;
CultureInfo english = new CultureInfo("En");
CultureInfo polish = new CultureInfo("Pl");
decimal amount = Decimal.Parse("29,80 zł", NumberStyles.Currency, polish);
Console.WriteLine(amount.ToString(english)); // 29.80

Custom Casting

There are two types of custom casting in C#:

  • An implicit casting (widening) e.g., casting Int32 to Int64.
  • An explicit casting (narrowing) e.g., casting double to float; in this case the cast operator () is required.

The implicit and explicit operators should be declared as public static methods.

Example: Define the following custom casting in the Point3D type:

  • narrowing casting (from Point3D to Point 2D) using the explicit operator
  • widening casting (from Point2D to Point3D) using the implicit operator
class Program
    static void Main(string[] args)
        // Use the explicit operator.
        Point2D p1 = (Point2D)new Point3D(4.0f, 2.0f, 1.0f); // narrowing from Point3D to Point2D
        // Use the implicit operator. The casting operator () is optional.
        Point3D p2 = (Point3D)new Point2D(8.0f, 6.0f); // widening from Point2D to Point3D
public struct Point3D
    public float X { get; set; }
    public float Y { get; set; }
    public float Z { get; set; }
    public Point3D(float x, float y, float z)
        : this() { /*...*/ }
    // Narrowing from a complex type Point3D to a simpler type Point2D.
    public static explicit operator Point2D(Point3D point)
        return new Point2D(point.X, point.Y);
    // Widening from a simple type Point2D to a more complex type Point3D.
    public static implicit operator Point3D(Point2D point)
        return new Point3D(point.X, point.Y, 0.0f);
public struct Point2D
    public float X { get; set; }
    public float Y { get; set; }
    public Point2D(float x, float y)
        : this() { /*...*/ }
notes/csharp/parsing.txt · Last modified: 2016/12/13 by admin