T3XT_3DIT0R
T3XT_3DIT0R

Reputation: 5

How do we return the value of a variable whose value is assigned inside an IF statement?

I have recently been making a calculator project and I have run into a small problem.

   internal static float Answer_Descision(string[] Data, float num1, float num2, string operand) 
   {
        string operand_types = ["*", "+", "/", "pwr", "-"];
        float ans;
        int Lenth_Of_Data = Data.Length;
        bool Help = Data[1] == "Help";
        if (Lenth_Of_Data == 1 && Help)
        {
            Console.WriteLine("The availible operands as of version 1.2 of the calculator are:\n1. \"+\"\n2. \"-\"\n3. \"*\"\n4. \"/\"\n5. \"pwr\"\n");
        }
        else if(operand == operand_types)
        { 
            ans = Operation_Descision(num1, operand, num2);
        }
        return ans;
   }

I basically want to assign a value to the variable "ans" inside the if statement.

But now when I do this it displays the following error for the return word: Use of unassigned variable "ans".

I want to know, how to assign the value of ans to it inside the if statement?

Upvotes: 0

Views: 55

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16069

You are getting this error because you have not assigned any value to ans variable at the time of defining it.

Assign default value to the variable where you are defining it.

float ans = 0f;  //Assign default vale

From MSDN:

A variable must be definitely assigned (Definite assignment) before its value can be obtained.

Upvotes: 4

Lucas S.
Lucas S.

Reputation: 702

As suggested by @Prasad, you must assign a value to the ans variable.

You can do it when you declare the variable:

float ans = 0f;

Or in your if, and don't forget the else statement as well. Thanks @dxiv for pointing this out.

if (Lenth_Of_Data == 1 && Help)
{
    ans = 0f;
    Console.WriteLine("The availible operands as of version 1.2 of the calculator are:\n1. \"+\"\n2. \"-\"\n3. \"*\"\n4. \"/\"\n5. \"pwr\"\n");
}
else if
{
    // ...
}
else
{
    ans = 0f;
}

Note you can use 0 or 0f as a value, since you are explicitly declaring the variable as a float.

If you were to use var instead, you need to specify 0f explicitly. Thus all these ways of declaring and assigning the ans are valid:

var ans = 0f;
float ans = 0;
float ans = 0.0;
float ans = 0f;

Upvotes: 1

Related Questions