Hossein Moradinia
Hossein Moradinia

Reputation: 6244

Convert object variable to decimal with best performance

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;
} 

Upvotes: 0

Views: 4994

Answers (4)

casperOne
casperOne

Reputation: 74540

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.

Upvotes: 2

FIre Panda
FIre Panda

Reputation: 6637

Use

decimal decimalValue = decimal.MinValue;

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

Hope this help.

Upvotes: 0

Ahmed Magdy
Ahmed Magdy

Reputation: 6040

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);

Upvotes: 1

Maged Samaan
Maged Samaan

Reputation: 1752

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

Upvotes: 1

Related Questions