Volunteer .NET Evangelist

A well oiled machine can’t run efficiently, if you grease it with water.
  首页  :: 联系 :: 订阅 订阅  :: 管理

TryParse Vs Parse

Posted on 2006-01-31 15:56  Sheva  阅读(1258)  评论(0编辑  收藏  举报
    With the .NET Framework 2.0, there is a great number of improvements to the Base Class Library, one big improvement is that when you want to parse a string input into any other primitive value type(except Enum), you can use the TryParse instead of Parse method, the reason is that TryParse method won't throw an exception if the conversion fails just as the following code illustrates:
Int32 result = -1;
if (Int32.TryParse("210s"out result))
{
    
// Parsing succeeds, now you can safely use the value.
}
else
{
    
// Parsing fails, this route is faster.
}


But if you use Parse method, you have to handle the situation when an exception would be thrown.
Int32 result = -1;
try
{
    result 
= Int32.Parse("210s")
}
catch(Exception)
{
    
// Parsing fails, this route is slower.
}


    Because throwing an exception and recovering from it is quite expensive, so you can improve your application's performance a lot by reducing the happening of exception as many times as possible.