views:

485

answers:

10

I understand it doesn't throw an Exception and because of that it might be sightly faster, but also, you're most likely using it to convert input to data you can use, so I don't think it's used so often to make that much of difference in terms of performance.

Anyway, the examples I saw are all along the lines of an if/else block with TryParse, the else returning an error message. And to me, that's basically the same thing as using a try/catch block with the catch returning an error message.

So, am I missing something? Is there a situation where this is actually useful?

+7  A: 

Where possible, use TryParse - using it is far cheaper then getting an exception thrown.

Oded
What if you have no reasonable way to handle `TryParse` failing though...?
Greg Beech
+21  A: 

Apart from the performance aspect that you mentioned yourself, there's also a semantic difference:

Using try/catch is meant for exceptional circumstances. Inputting invalid data is something you expect, not something exceptional.

Mark Byers
+1 for mentioning exceptions vs validation. One of my pet peeves!
Jason Down
I'd just add that alot of people probably us it in the if/else way and using .Parse inside a try/catch might throw (excuse the pun) some people at first.
Nate Bross
+1  A: 

If you need to set a default value on failed parsing, TryParse along with an if is a great way to do so.

kmontgom
A: 

For cases that either don't mind setting the value to 0 on a failed parse (perhaps invalid input) or cases where you want brevity, the return code of TryParse allows that.

mrjoltcola
+1  A: 

Well int.TryParse returns a bool allowing you to test if it was successful instead of catching an exception. I usually use it in situations where if the information was successfully translated, I want to use it, but if not, it's not important, I can ignore the failure in-so-far as I want to use a default unless I get a meaningful value in which case I'll override it, but if the value wasn't meaningful, I'll keep the default.

The theory says that exceptions are inherently expensive, and thus you shouldn't use them to dictate program flow. You should catch them where something is semantically wrong, rather than something that may be interpreted as data flow.

BenAlabaster
A: 

Everytime you have a parse to perform as it is pretty less expensive to use than an Exception, plus you can make it part of a simple if statement instead of a big try...catch block.

Will Marcouiller
A: 

I'm no c# monkey but...

An exception interrupts normal code flow by transferring processing to the catch block.

TryParse will give you more control (eg highlight an error in a text box) rather then relying on the Exception mechanism.

gbn
+10  A: 

It's pretty much as simple as this: Use Parse if you want an exception when you encounter invalid data; use TryParse if you don't. Your question seems, therefore, to be:

Why would you not want an exception if data is invalid?

Exceptions should only be used for exceptional cases, and the data being invalid might not be an exceptional case. Maybe you're writing a data cleansing program that's expecting to get invalid data and will try to infer what a reasonable value is when the data is invalid. Maybe the data isn't all that important and you can just skip the record that contains it.

It depends on context, and having the choice of Parse and TryParse methods lets you choose the appropriate parsing mechanism for yours.

Greg Beech
A: 

If you're doing validation of input on a form, you could set the ErrorProvider on the control (or a MessageBox or some other notification) when it returns false. It's not an exceptional case because like others have said, you should plan for it.

Austin Salonen
+1  A: 

Suppose you're reading a log file:

public IEnumerable<LogEntry> GetAllValidEntries() {
    while (!logReader.Finished) {
        string nextLine = logReader.ReadLine();
        LogEntry nextEntry;

        if (TryParseLogEntry(nextLine, out nextEntry))
            yield return nextEntry;
    }
}

private bool TryParseLogEntry(string line, out LogEntry logEntry) {
    logEntry = null;

    if (string.IsNullOrEmpty(line))
        return false;

    string[] cells = line.Split(';');
    if (cells.Length < 3)
        return false;

    DateTime time;
    decimal price;
    int quantity;

    // We just want to read this line of text as a LogEntry
    // IF it is valid; otherwise, there's no reason to throw
    // an error in the user's face
    if (!DateTime.TryParse(cells[0], out time) ||
        !decimal.TryParse(cells[1], out price) ||
        !int.TryParse(cells[2], out quantity))
        return false;

    logEntry = new LogEntry(time, price, quantity);
    return true;
}

Since the whole purpose of the above code is to extract valid items from a sequence (which is presumably expected to contain some invalid items), I think TryParse methods make a lot more sense in this case than Parse methods, which demand valid input.

Dan Tao