TryParse() in one line–when to use it, when to avoid it

Note: The code samples shown below are meant to run in LinqPad as “C# Statements”. You can use the free version, but it’s well worth paying for.

Almost all types (every one I can think of, but I’m not going to commit and say “all”) have both a .Parse() and .TryParse() method, the differences between which are discussed at As a general rule, we try and use .TryParse() everywhere.

The one down side to .TryParse() is that it requires a little extra code–an output variable, and a result variable, and you’ll probably need to set a default value in case the parsing fails. You can accomplish this in one line of code with the right syntax that at first doesn’t look like it should work.

Here’s an example of how to do .TryParse() in one line, showing a syntax which works and one which doesn’t (.Dump() is a method specific to LinqPad).

string _int = "8675309";

int i1 = int.TryParse(_int, out i1)
	? i1
	: 0;

Output: 8675309

//This doesn't work
//var i2 = int.TryParse(_int, out i2)
//	? i2
//	: 0;

It’s interesting how the explicitly typed variable works, but the implicitly typed one doesn’t. The same thing happens with a GUId:

string _guid = "d09eccda-533a-4772-b589-dbc5676fb690";

//This works
Guid g1 = Guid.TryParse(_guid, out g1) 
	? g1 
	: Guid.Empty;

output: d09eccda-533a-4772-b589-dbc5676fb690

//This does not:
//var g2 = Guid.TryParse(_guid.ToString(), out g2)
// 	? g2
// 	: Guid.Empty;

So we know implicit typing isn’t going to work. Are there any other places we’ve found you need to be careful? Yes, one more so far–Booleans. Based on the patterns above, you’d expect this to work:

string _bool = "false";
bool b1 = bool.TryParse(_bool, out b1);

output: true

Go try that in LindPad and see what happens. Spoiler alert: b1 is true, not false. The result of .TryParse() is a Boolean, and instead of assigning the output value to b1, the result is being assigned to b1. Instead, you need to use the longer syntax to make Booleans work correctly:

string _bool = "false";
bool b2;
bool b3 = bool.TryParse(_bool, out b2);

output: true

That will end up with the correct values assigned.

So there you have it–how to handle a .TryParse() in one line, and a couple of pitfalls in doing so. Hope that helps!