开发者

C#: When should I use TryParse?

开发者 https://www.devze.com 2022-12-23 03:59 出处:网络
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 thin开发者_如何转开

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 thin开发者_如何转开发k 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?


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.


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.


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


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.


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


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.


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号