Parse vs TryParse in .Net

TryParse is a more advanced and powerful version of the Parse() method.

Mendel Bakaleynik
3 min readJul 10, 2019

Parse()

The Parse method takes a string as an argument and attempts to translate it back to the specified type. Here’s what it looks like in action.

return Int32.Parse("101"); // Will return -> 101
return bool.Parse("true"); // Will return -> True
return bool.Parse(1); // Will fail since argument is not a string.

The problem with the Parse method is that if the argument that is passed to it is invalid, such as bool.Parse(2), bool.Parse("asfsad"), Int32.Parse(null) it will throw an ArgumentNullException error. We want to have our program be able to gracefully handle bad input so we need a more robust method that doesn’t throw errors in the face of bad data.

Enter the TryParse method.

TryParse()

TryParse works a little differently. It takes an input, just like before, and attempts to translate it, just like before. But this method is special since it returns two values, instead of the usual one. The method itself returns a bool value if it was able to successfully translate the argument into the correct format.

That means, we can check the method’s return value to see if the translation/parsing went alright. Here’s what that looks like: (ignore the second parameter for now. We’ll discuss that in a moment.)

return Int32.TryParse("101", out int ignoreMeForNow); 
// Will return -> True
return bool.TryParse("true", out bool ignoreMeForNow);
// Will return -> True
return Int32.TryParse(null, out int ignoreMeForNow);
// Will return -> False
return bool.TryParse("This is gibberish", out bool IgnoreMeForNow);
// Will return -> False

Great! Now we learned that the TryParse method itself return a boolean value. But where do I get my actual, translated, value?

You get it from the out variable.

The TryParse method requires that you have an out parameter, which holds the translated value. You can define the variable above the method, or inside the method. You can also ignore the out variable value if all you care about is using the TryParse method to validate a boolean value, but you still have to setup the out variable correctly.

Let’s see some examples.

// You can define your 'out' variable above the method call.
var outValue;
bool.TryParse("true", out outValue);
return outValue; // Will return -> true
// You can define the 'out' variable inside the method.
Int32.TryParse("123", out int value);
return value; // Will return -> 123
// You can ignore the 'out' variable and just check a boolean value.
return bool.TryParse(null, out bool ignoreThisVariable);
// Will return -> false
// Remember, this returns false since we're returning whether the TryParse method could translate the value it was given.

If we wanted to use the TryParse method to check a configuration setting in our code, return the proper true/false statement, and handle bad input, it would look like this.

function bool ReturnConfigSettingBool(string configSettingString)
{
return bool.TryParse(configSettingString, out bool ignoreThis);
}

Be Aware of False Positives

You should be aware, if the TryParse conversion fails, the out parameter will be false . You should check and guard against this.

function bool RetunConfigSettingBool(string configSettingString)
{
var x = bool.TryParse(configSettingString, out bool boolValue);

// Check 'x' to see if the conversion failed or not. If it failed, we're going to default our bool value to true, just for this example.
if(x == false)
{
// Right now boolValue == false. We're resetting it.
boolValue == true;
}
// return ...
}

That’s all there is to it!

Remember,

  • Parse() returns the translated value or an error.
  • TryParse will never return an error.
  • TryParse returns 2 things. 1) A boolean value saying if the translation went well or not, and 2) an out variable of the translated value.
  • If TryParse fails to convert, it will set the out param to false .

Advanced

A clever way to use the TryParse method is to use a ternary operator to craft a conditional ref expression.

Let’s say you wanted to evaluate a configuration setting, return the proper true/false statement, prevent errors due to bad input, and default to True in case of bad input, it would look like this.

public bool IsConfigSettingTrue(string configSettingString)
{
return bool.TryParse(configSettingString, out bool ignoreThisVar) ? value : true;
}

--

--

Mendel Bakaleynik

FullStack Dev. Working to bring acts of goodness and kindness to the world.