I get the error. The way I am looking at is I want the value that is returned from dayrental() * 19.95 to be stored in rental.
Use of unassigned local variable ‘rental’
private void button1_Click(object sender, EventArgs e)
{
double rental;
if (checkBox1.Checked == true)
rental = dayrental() * 19.95;
label4.Text = Convert.ToString(rental);
}
private void label4_Click(object sender, EventArgs e)
{
}
public double dayrental()
{
var timeSpan = dateTimePicker2.Value - dateTimePicker1.Value;
var rentalDays = timeSpan.Days;
return (double) rentalDays;
//label4.Text = Convert.ToString(rentalDays);
}
The reason this message appears is that the compiler does not allow you to use an unassigned variable.
Let’s here consider that your
CheckBox.Checkedproperty is false, what happens? You’re trying to convert the value of your variable. At the end, you’re using it! But how should the compiler know what value it’s worth?Here’s a link that explains this error in depth:
Compiler Error CS0165.You need to tel the compiler that you know what you’re doing. How? By initializing a default value to your variable. It may be some of the following:
or
Or else, you may want that your form displays no value at all when this
CheckBoxis notChecked. Then, you would need a nullable type of double.or
While using this nullable double value type, this will allow you to display nothing when the
CheckBox.Checked = false. Now, you should ask yourself whether you want zero (0) to be displayed when theCheckBoxis notChecked.By the way, the
ifcondition only requires a boolean expression in its parentheses, and that’s exactly what theCheckBox.Checkedproperty is, so no need to compare it againsttrue.Following this simple rule, you should be able to never ever again get this error.
Does this help?