Parse() vs TryParse() vs Convert Class Methods in C#

Introduction

In C#, Parse(), TryParse(), and Convert methods are commonly used to convert strings into other data types like integers, decimals, or dates. Each of these methods works differently when dealing with invalid input, and choosing the right one depends on the use case.

Parse() Method

The Parse() method is used to convert a string to a specific data type. It throws an exception if the conversion fails, so it’s best used when you’re sure the string contains a valid value.

Example: Using Parse()

string numberString = "123";
int number = int.Parse(numberString);

Console.WriteLine(number);  // Output: 123
        

In this example, Parse() successfully converts the string "123" into an integer. If the string were not a valid number, it would throw a FormatException.

TryParse() Method

The TryParse() method attempts to convert a string to a specific data type. It returns true if the conversion succeeds and false if it fails, without throwing an exception. This makes it safer to use when dealing with potentially invalid input.

Example: Using TryParse()

string numberString = "123";
bool success = int.TryParse(numberString, out int number);

if (success)
{
    Console.WriteLine(number);  // Output: 123
}
else
{
    Console.WriteLine("Invalid input");
}
        

In this example, TryParse() converts the string to an integer if the conversion is valid. If the conversion fails, no exception is thrown, and it returns false.

Convert Class Methods

The Convert class provides methods to convert a value to a specified type. If the input is null, it returns the default value for the target type (e.g., 0 for integers). It throws an exception if the conversion fails for non-null inputs.

Example: Using Convert.ToInt32()

string numberString = null;
int number = Convert.ToInt32(numberString);

Console.WriteLine(number);  // Output: 0
        

In this example, Convert.ToInt32() converts a null string to 0. If the string were a non-null, invalid number, it would throw a FormatException.

Comparison Between Parse(), TryParse(), and Convert

Method Throws Exception Handles Null Return Type
Parse() Yes, throws exception on invalid input. No, throws exception on null. Converted value or exception.
TryParse() No, returns false on invalid input. No, returns false on null. true or false, and converted value through out parameter.
Convert Yes, throws exception on invalid non-null input. Yes, returns default value on null. Converted value or exception.

Key Points to Remember

  • Use Parse() when you are sure the string contains valid data and want an exception to be thrown if it doesn’t.
  • Use TryParse() for safer conversions where you handle invalid input gracefully without exceptions.
  • Use Convert when you need to handle null values without exceptions, returning default values for the target type.