No overload for method tryparse takes 1 arguments RRS feed

  • Question

  • User-1499457942 posted


      I have below code on which error comes

    decimal amount = decimal.TryParse(sqlReader.GetValue(1)).ToString();

    Tuesday, September 4, 2018 4:43 PM

All replies

  • User475983607 posted

    The openly published reference documentation explains how to use the decimal.TryParse(string s, out decimal result) method. 



    Tuesday, September 4, 2018 4:45 PM
  • User753101303 posted


    Which is correct. If you look at the doc the usual pattern for TryParse is ;
    - you pass the value you want to convert and the value that should receive the converted value
    - it returns a boolean that tells if the conversion succeeded

    You have also an extra ToString.

    In this case you are perhaps going through uneedeed hops. Isn't the db side column you are trying to retrieve already a decimal ? Or if you are tyring with dealing with DBNull.Value (which comes from before having support for nullable value types), I would add my own extension method to hide this and use just nullable types to be able to write maybe something such as :

    decimal? amount=sqlReader.Get<decimal?>(1);

    Edit: I meant if the db side column is a decimal you could just use :

    decimal amount = sqlReader.GetDecimal(1);

    Tuesday, September 4, 2018 5:16 PM
  • User-893317190 posted

    Hi JagjitSingh,

    As mgebhard's link shows,you could use the method TryParse as follows.

     decimal amount;
                //if the first parameter could be converted to decimal 
                // the method decimal.TryParse return true and the second 
                // parameter will be assigned value
                if (decimal.TryParse(sqlReader.GetValue(1).ToString(), out amount))
                    // here use the variable amount

     You could also use  the keyword "as".

    Below is my code.

     using (SqlDataReader reader=com.ExecuteReader())
                        if (reader.HasRows)
                            while (reader.Read())
                                decimal? a = reader.GetValue(1) as decimal?;
                                if (amount.HasValue)
                                    decimal amount = a.Value;

    For more information about the keyword as , please refer to  https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as

    Best regards,

    Ackerly Xu

    Wednesday, September 5, 2018 6:09 AM