-1

I keep getting errors of unassigned variable below which is TotalAmount = TotalQuantity * UnitPrice. Please advise.

private void button1_Click(object sender, EventArgs e)
{
    string client;
    string date;
    string telNumber;

    const decimal TaxRate = 0.43M;

    uint Quantity, Amount, Total;

    decimal TotalOrder, TaxAmount, SalesTotal, TotalQuantity;
    decimal UnitPrice, AmountTended, Difference, TotalAmount;


    Console.SetCursorPosition(10, 5);
    Console.ForegroundColor = ConsoleColor.Yellow;
    client = Console.ReadLine();

    Console.SetCursorPosition(10, 7);
    Console.ForegroundColor = ConsoleColor.Yellow;
    client = Console.ReadLine();

    Console.SetCursorPosition(58, 5);
    Console.ForegroundColor = ConsoleColor.Yellow;
    date = Console.ReadLine();

    Console.SetCursorPosition(67, 7);
    Console.ForegroundColor = ConsoleColor.Yellow;
    telNumber = Console.ReadLine();

    //TotalQuantity
    bool test = false;
    do
    {
        try
        {
            Console.SetCursorPosition(2, 12);
            Console.Write(" ");

            Console.SetCursorPosition(2, 12);
            TotalQuantity = Convert.ToDecimal(Console.ReadLine());
            test = false;
        }
        catch
        {
            test = true;
        }
    } while (test);

    //Item Description

    Console.SetCursorPosition(18, 12);
    Console.ForegroundColor = ConsoleColor.Yellow;
    telNumber = Console.ReadLine();

    //Unit Price

    bool test2 = false;
    do
    {
        try
        {
            Console.SetCursorPosition(47, 12);
            Console.Write(" ");

            Console.SetCursorPosition(47, 12);
            UnitPrice = Convert.ToDecimal(Console.ReadLine());
            test2 = false;
        }
        catch
        {
            test2 = true;
        }
    } while (test2);

    //Computations

    //TotalAmount
    **TotalAmount = TotalQuantity*UnitPrice;
    **

    Console.SetCursorPosition(65, 12);
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.Write("P ");
    Console.WriteLine(TotalQuantity*UnitPrice);
    Console.ReadLine();
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Puchicha
  • 1
  • 5
  • are you compiling with ** and ** around the TotalAmount? – d.moncada Dec 09 '14 at 03:11
  • I disagree that this is a duplicate. Yes, it's the same error message. But the other question involves a _genuinely_ unassigned variable, whereas here it's simply a failure of the compiler to identify the assignment. In addition, the only suitable answer in the other question is to initialize the variable, whereas here these variables do not actually need to be pre-initialized before they are actually assigned for real. It is misleading to treat this question as a duplicate of the other. – Peter Duniho Dec 09 '14 at 03:34
  • I do checked the answers and questions before posting this one, and thanks to Mr Grant, I got an answer and also Thank you Sir Peter – Puchicha Dec 09 '14 at 03:42

2 Answers2

2

According to the C# definite assignment rules, neither TotalQuantity or UnitPrice are definitely assigned. You, as a human being, are able to look at the code and know they are definitely assigned. But the compiler is not expected to analyze the use and assignment of the variables test and test2 as they pertain to the flow of the loop. So you get a compile-time error.

The right way to fix this is to create a helper method that handles the input of these items. That will not only ensure you don't have that copy/pasted code, you'll use the method's return value to assign to each variable, ensuring that the compiler can tell the variable is definitely assigned.

For example:

private void button1_Click(object sender, EventArgs e)
{
    string client;
    string date;
    string telNumber;

    const decimal TaxRate = 0.43M;

    uint Quantity, Amount, Total;

    decimal TotalOrder, TaxAmount, SalesTotal, TotalQuantity;
    decimal UnitPrice, AmountTended, Difference, TotalAmount;


    Console.SetCursorPosition(10, 5);
    Console.ForegroundColor = ConsoleColor.Yellow;
    client = Console.ReadLine();

    Console.SetCursorPosition(10, 7);
    Console.ForegroundColor = ConsoleColor.Yellow;
    client = Console.ReadLine();

    Console.SetCursorPosition(58, 5);
    Console.ForegroundColor = ConsoleColor.Yellow;
    date = Console.ReadLine();

    Console.SetCursorPosition(67, 7);
    Console.ForegroundColor = ConsoleColor.Yellow;
    telNumber = Console.ReadLine();

    //TotalQuantity
    TotalQuantity = PromptDecimal(2);

    //Item Description

    Console.SetCursorPosition(18, 12);
    Console.ForegroundColor = ConsoleColor.Yellow;
    telNumber = Console.ReadLine();

    //Unit Price    
    UnitPrice = PromptDecimal(47);

    //Computations

    //TotalAmount
    **TotalAmount = TotalQuantity*UnitPrice;
    **

    Console.SetCursorPosition(65, 12);
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.Write("P ");
    Console.WriteLine(TotalQuantity*UnitPrice);
    Console.ReadLine();
}

where:

decimal PromptDecimal(int promptLine)
{
    while (true)
    {
        Console.SetCursorPosition(promptLine, 12);
        Console.Write(" ");

        Console.SetCursorPosition(promptLine, 12);

        decimal result;

        if (decimal.TryParse(Console.ReadLine(), out result))
        {
            return result;
        }
    }
}
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • I would also try to use and study this one, Thank you sir – Puchicha Dec 09 '14 at 03:44
  • What does prompt, Promptline actually do sir? – Puchicha Dec 09 '14 at 03:46
  • @Puchicha: do you mean `PromptDecimal()`? It's the new method you will add and use instead of the loops you have now. It does the same thing your code did before, except in a reusable method, which returns the `decimal` value that was entered. I will edit the answer so that it provides more context about my suggested change. – Peter Duniho Dec 09 '14 at 03:50
  • So that means sir, it will also generate the same output in an easy way if i use the first code i made then add your next code. Thank you sir. – Puchicha Dec 09 '14 at 03:59
  • @Puchicha: you will change your original code so that it looks the way I show in my answer (i.e. the loops removed, and replaced with calls to this new method), and then you'll add that new method itself. – Peter Duniho Dec 09 '14 at 04:09
  • Thank you sir, but an error says an object is An object reference is required for the non-static field, method, or property on PromptDecimal(47); and PromptDecimal(2); – Puchicha Dec 09 '14 at 04:29
  • You must have put the method in a different class from where you are using it. You can do that if you really want to of course, but you still have to follow the rules of C# if you do: either make the method `static` and refer to it via the containing type name, or create an instance of the containing type before you try to call it. Personally, I'd just put it in the same class with your existing `button1_Click() `method for now. Why complicate things? – Peter Duniho Dec 09 '14 at 10:02
2

You're only assigning values to those variables inside the try/catch block, and the compiler has no idea if the code in the try block will successfully assign a value before you get to the section of code later on, where you're multiplying the values.

Assign them a default value when you define them.

decimal UnitPrice = 0, TotalQuantity = 0;

This gets your program compiling at least. If the try block does fail for some unexpected reason, you'll end multiplying two zeroes and your program will move forward. That may or may not be desirable, depending on your situation.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • Im only a week old in c#, i will try what you suggested and put it before the try catch thing, is that correct? Thank you sir – Puchicha Dec 09 '14 at 03:19
  • 1
    IMHO, assigning default values should be a last resort for dealing with this error message. It is usually possible to structure the code so that the compiler can correctly comprehend the actual flow of execution, and doing so pretty much always makes the code more expressive and understandable. It's a win-win. :) – Peter Duniho Dec 09 '14 at 03:32
  • I will study how that work sir, thanks again, I'm new in programming and i'm practicing on console app, thanks sir – Puchicha Dec 09 '14 at 03:45