Is it possible to construct an object of a class or declare a variable directly in the return of a method?

0

Suppose I have this method ...

    private BigInteger Numero(string cadena)
            {
               if (CadenaConValor(cadena) != 0 && CadenaOk(cadena))
               {
                   BigInteger n;
                   return n = BigInteger.Parse(cadena);
               }
               return 0;
            }

Could in the return simplify the syntax to directly return the converted cadena string, without having to create the variable n in the previous line?

As I expose in the title, it also happens to me when I try to return objects which I have to instantiate before I can return them.

    
asked by Edulon 22.09.2017 в 17:51
source

1 answer

3

Sure. You simply delete the assignment and return the return value of the method BigInteger.Parse :

 private BigInteger Numero(string cadena)
{
   if (CadenaConValor(cadena) != 0 && CadenaOk(cadena))
   {
       return  BigInteger.Parse(cadena);
   }
   return 0;
}

And using a ternary operator you can simplify the code even more:

 private BigInteger Numero(string cadena)
{

   return (CadenaConValor(cadena) != 0 && CadenaOk(cadena)) ?  BigInteger.Parse(cadena) : 0;
}
    
answered by 22.09.2017 / 17:55
source