开发者

Convert object variable to decimal with best performance

开发者 https://www.devze.com 2023-03-04 20:53 出处:网络
I Use fo开发者_运维问答llowing Code for Convert an object value to a decimal.how can i write this code for best performance?

I Use fo开发者_运维问答llowing Code for Convert an object value to a decimal.how can i write this code for best performance?

decimal a;
try
{
   a=decimal.Parse(objectvariable);
}
catch(Exception)
{
   a=0;
} 


Instead of using the Parse method, which forces you to catch an Exception, you should use the static TryParse method on the Decimal struct.

This will try to perform the parse, and if it fails, return a boolean value determining whether or not you succeeded. The results of the parse, if successful, are returned through an out parameter that you pass in.

For example:

decimal a;

if (Decimal.TryParse(objectvariable, out a))
{
    // Work with a.
}
else
{
    // Parsing failed, handle case
}

The reason is this is faster is that it doesn't rely on an Exception to be thrown an caught, which in itself, is a relatively expensive operation.


i always use decimal.TryParse() instead of decimal.Parse() Its safer, and faster i guess


Have you tried Decimal.TryParse Method

decimal number;
if (Decimal.TryParse(yourObject.ToString(), out number))
   Console.WriteLine(number);
else
   Console.WriteLine("Unable to parse '{0}'.", value);


Use

decimal decimalValue = decimal.MinValue;

if(decimal.TryParse(objectvariable, out decimalValue))
        return decimalValue;
else
        return 0;

Hope this help.

0

精彩评论

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