0

I Use following 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;
} 
casperOne
  • 73,706
  • 19
  • 184
  • 253
Hossein Moradinia
  • 6,116
  • 14
  • 59
  • 85

4 Answers4

2

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.

Community
  • 1
  • 1
casperOne
  • 73,706
  • 19
  • 184
  • 253
1

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

Maged Samaan
  • 1,742
  • 2
  • 19
  • 39
1

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);
Ahmed Magdy
  • 5,956
  • 8
  • 43
  • 75
0

Use

decimal decimalValue = decimal.MinValue;

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

Hope this help.

FIre Panda
  • 6,537
  • 2
  • 25
  • 38