Home > database >  Query about conditional
Query about conditional

Time:11-17

People I need make a funtion where return true or false. My code has a mistake I don´t know how to do it.

public bool Existe()
{
    if (cbocarpeta.Text == "FORMULARIO N1 - DDJJ")
    {
         var exist = db.Ficha_Escribanos.SingleOrDefault(f => f.ApeyNom == txtapeynom.Text && f.Nro_Afiliado == txtafiliado.Text

         result = exist != null ?  true :  false; 
    }
}

I want that to make it do 'Return'

Error CS0161 'Form1.Exists()': not all code pathnames return a value

CodePudding user response:

The problem is that your are not returning a value, if your condition in the if is not fulfilled then you have to return also a value.

if you want to do something special if the formular is not found add an else statement and return also a value there.

Try the following:

    public bool Existe()
{
    if (cbocarpeta.Text == "FORMULARIO N1 - DDJJ")
    {
         var exist = db.Ficha_Escribanos.SingleOrDefault(f => f.ApeyNom == txtapeynom.Text && f.Nro_Afiliado == txtafiliado.Text);

         return exist != null;
    }
    // you need to return something if the if cbocarpeta.Text != "FORMULARIO N1 - DDJJ"
    return false;

}

CodePudding user response:

Any non-void method can only end in one of two ways: Either by returning a value or by throwing an exception.
Your method does not return any value, and it will only throw under very specific circumstances.
To fix it, you must make sure it either returns a value or throws every time it's called.

Also, unless you want your method to throw an exception if there is more than one item that the predicate returns, you better use Any instead of SingleOrDefault.
This will both simplify your code and will have better performance (though to be honest that would be completely negligible in this case).

All in all, this method can be compressed to a single line of code:

public bool Existe()
   => cbocarpeta.Text == "FORMULARIO N1 - DDJJ"
   && db.Ficha_Escribanos.Any(
       f => f.ApeyNom == txtapeynom.Text 
       && f.Nro_Afiliado == txtafiliado.Text);
  • Related