Monday, October 25, 2010

TryParse (.NET C#)

Back in the old days of .NET 1.x it was common to have this sort of code to convert a string into an int variable:


int x = 0;
try
{
x = int.Parse("bad");
}
catch (Exception)
{
    //...
}

While the code above was effective it required a try catch to handle errors. As of .NET 2.x there is a TryParse method in addition to the original Parse method on a variety of types. The code is a lot simpler. The return value of TryParse is a bool so your code can be a little less messy. Wrapping things in an if statement is a lot better than a try/catch for a variety of reasons.


int x = 0;
int.TryParse("bad", out x);

MSDN Int32.TryParse

No comments:

Post a Comment