[SOLVED] Boolean Function c# not all code return a value

Issue

What am I doing wrong here?

At the end of the function, I’m returning the result.

 public bool  isStipends() 
    {
        try
        {
            bool result = true;
            if (tbstipend.Text == "" || tbstipend.Text == "Required")
            {
                tbstipend.Text = "Required";
                tbstipend.BackColor = Color.Red;
                tbstipend.ForeColor = Color.White;
                result =  false;
            }
            else if  (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
            {
                tbstipendperperiod.Text = "Required";
                tbstipendperperiod.BackColor = Color.Red;
                tbstipendperperiod.ForeColor = Color.White;
                result = false;
            }

            else  if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
            {
                tbstipendsperinterval.Text = "Required";
                tbstipendsperinterval.BackColor = Color.Red;
                tbstipendsperinterval.ForeColor = Color.White;
                result = false;
            }

            else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
            {
                tbstipendrate.Text = "Required";
                tbstipendrate.BackColor = Color.Red;
                tbstipendrate.ForeColor = Color.White;
                result =  false;
            }
            else
            {
                return result;
            }

        }
        catch 
          {
             return false;
          }
    }

In the code behind of the button, I call:

 private void btnupdatestipends_Click(object sender, EventArgs e)
    {
        try
        {
            if (isStipends() == true)
            {
                MessageBox.Show("TEST");
            }
        }
        catch { }
    }

However, it gives me an error on the function itself.

Error 3 ‘AddressBookMaint.Form1.isStipends()’: not all code paths return a value C:\Win\AddressBookMaint\AddressBookMaint\Form1.cs 5040 22 AddressBookMaint

Any suggestions?

Thank you.

Solution

You either need to return something in your catch:

public bool Method() {
    try {
        return true;
    }
    catch {
        return false;
    }
}

Or just return a single value at the bottom:

public bool Method() {
    bool result = false;
    try {
        ...
        result = true;
    }
    catch {}

    return result;
}

Answered By – Neil Smith

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *