How can I make insuranceCost
available outside the if
statement?
if (this.comboBox5.Text == "Third Party Fire and Theft")
{
double insuranceCost = 1;
}
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.
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.
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.
You can also use the if statement scriptblock to assign a value to a variable.
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
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With