Search code examples
c#booleandecimaltryparse

Having trouble with data types using TryParse in C#


The follow is a button on a form. The user enters a dollar amount in to the subtotal text box and presses the calculate button. It then figures a discount and displays the invoice total in a text box at the bottom of the form. We are suppose to use the Parsing method to convert the entry to decimal if a "$" gets entered with the subtotal amount. My question is about the data type sucess. I now it is Bool because it is a 1 or 0.

When I try and build the form I get this error:

Error 1 Cannot implicitly convert type 'bool' to 'decimal'

namespace InvoiceTotal
{
public partial class frmInvoiceTotal : Form
{
    public frmInvoiceTotal()
    {
        InitializeComponent();
    }

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        decimal sucess = 0m;
        decimal subtotal = Decimal.TryParse(txtSubtotal.Text, out sucess);
        decimal discountPercent = .25m;
        decimal discountAmount = Math.Round(subtotal * discountPercent,2);
        decimal invoiceTotal = Math.Round(subtotal - discountAmount,2);

        txtDiscountPercent.Text = discountPercent.ToString("p1");
        txtDiscountAmount.Text = discountAmount.ToString(); // ("c");
        txtTotal.Text = invoiceTotal.ToString(); // ("c");

        txtSubtotal.Focus();
    }

I guess I am not declaring the right data type for the variable "sucess"? If someone could help point me in the right direction I would greatly appreciate!

*Error 1 Cannot implicitly convert type 'bool' to 'decimal'

I am using Visual Studio Professional 2012 on a Windows 8.1 machine.


Solution

  • While the other answers are all correct, I wanted to expand upon them. The reason for the TryParse method is to allow you better control program flow in the event of invalid input. In other words what would you like to happen if the input is wrong:

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        decimal subtotal;
    
        if (!decimal.TryParse(txtSubtotal.Text, out subtotal))
        {
            //Display some warning to the user
            MessageBox.Show(txtSubtotal.Text + " is not a valid number");
    
            //don't continue processing input
            return;
        }
    
        //input is good, continue processing
        decimal discountPercent = .25m;
        decimal discountAmount = Math.Round(subtotal * discountPercent,2);
        decimal invoiceTotal = Math.Round(subtotal - discountAmount,2);
    }
    

    In some cases, it's not necessary to control the program flow in the event of bad date because you'd just throw an exception anyway. In that case you can just use Decimal.Parse which would throw a FormatException.