Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a variable outside of an 'if' statement

Tags:

c#

How can I make insuranceCost available outside the if statement?

if (this.comboBox5.Text == "Third Party Fire and Theft")
{
    double insuranceCost = 1;
}
like image 633
G Gr Avatar asked Jul 26 '12 07:07

G Gr


People also ask

How do you use a variable outside of an IF statement?

If you define the variable inside an if statement, than it'll only be visible inside the scope of the if statement, which includes the statement itself plus child statements. You should define the variable outside the scope and then update its value inside the if statement.

Can you use a variable outside a function?

Variables declared outside of any function become global variables. Global variables can be accessed and modified from any function. In the above example, the variable userName becomes a global variable because it is declared outside of any function.

Can you access the variables defined inside a function outside its body?

Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined.

Can you assign a variable in an if statement?

You can also use the if statement scriptblock to assign a value to a variable.


3 Answers

Define it outside of the if statement.

double insuranceCost;
if (this.comboBox5.Text == "Third Party Fire and Theft")
        {
          insuranceCost = 1;
        }

If you are returning it from the method then you can assign it a default value or 0, otherwise you may get an error, "Use of unassigned variable";

double insuranceCost = 0;

or

double insuranceCost = default(double); // which is 0.0
like image 120
Habib Avatar answered Oct 20 '22 01:10

Habib


In addition to the other answers, you could just inline the if in this case (parenthesis added only for clarity):

double insuranceCost = (this.comboBox5.Text == "Third Party Fire and Theft") ? 1 : 0; 

Replace 0 with whatever value you want to initialize insuranceCost to, if the condition does not match.

like image 32
Heinzi Avatar answered Oct 20 '22 02:10

Heinzi


    double insuranceCost = 0; 
    if (this.comboBox5.Text == "Third Party Fire and Theft") 
    { 
        insuranceCost = 1; 

    } 

Declare it before the if statement, giving a default value. Set the value inside the if. if you don't give a default value to the double, you will get an error at compile time. For example

double GetInsuranceCost()
{
        double insuranceCost = 0; 
        if (this.comboBox5.Text == "Third Party Fire and Theft") 
        { 
            insuranceCost = 1; 

        } 
        // Without the initialization before the IF this code will not compile
        return insuranceCost;
}
like image 32
Steve Avatar answered Oct 20 '22 02:10

Steve