TheVillageIdiot
TheVillageIdiot

Reputation: 40507

which version of the code below is right?

Hi I found this function in a utilities code file:

Version 1:

public static bool IsValidLong(string strLong)
{
    bool result = true;
    try
    {
        long tmp = long.Parse(strLong);
    }
    catch (Exception ex)
    {
        result = false;
    }
    return result;
}

I want to replace this (and validators for other types) with following:

Version 2:

public static bool IsValidLong(string strLong)
{
    long l;
    return long.TryParse(strLong, out l);
}

which version is better and why?

Upvotes: 3

Views: 112

Answers (4)

glenngao
glenngao

Reputation: 115

version 2 is better, wrap code in a try/catch block will affect performance, I think the TryParse() implementation will not use this approach.

Upvotes: 0

Robben_Ford_Fan_boy
Robben_Ford_Fan_boy

Reputation: 8720

In the second version the FW is encapsulating the behaviour in the first version for you. I would say that the two examples are equivalent but I would say the code in the second example is cleaner.

Upvotes: 1

Inv3r53
Inv3r53

Reputation: 2959

I prefer the second one since both do same and second one is less code.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630489

The first exists because the 2nd didn't at one point (Int64.TryParse() was added in .Net 2.0)...use the second version, why not take advantage of the features the framework adds in the newer releases if they're available to you? :)

The second is much clearer, leaner and more maintinable...I'd say it's a much better approach... it just wasn't available before.

Also, I believe TryParse() doesn't actually throw any exception internally, so it would be slower in a successful parse, but much quicker/less expensive than throwing an exception in the case of a failed parse.

Upvotes: 3

Related Questions