Access to a variable outside the if statement

How to make insuranceCostavailable outside the instructions if?

if (this.comboBox5.Text == "Third Party Fire and Theft")
{
    double insuranceCost = 1;
}
+5
source share
3 answers

Define it outside the if statement.

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

If you return it from a method, you can set it to the default value or 0, otherwise you may receive the error message "Using an unassigned variable";

double insuranceCost = 0;

or

double insuranceCost = default(double); // which is 0.0
+14
source

In addition to the other answers, you can simply insert ifin this case (brackets are added only for clarity):

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

Replace with 0any value you want to initialize insuranceCostto if the condition does not match.

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

    } 

if, . if. , .

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;
}
+3
source

All Articles