Home > Mobile >  How can I validate these variables without an if else statement?
How can I validate these variables without an if else statement?

Time:11-04

I'm very new to c# so please excuse my lack of knowledge. I'm just trying to check the following:

  • "CardNumberLength" = 16
  • "CardPINLength" = 3
  • "CardNameHasSpace" 0 I don't want to use an if else statement, is there another way?

The code:

public bool Validate()
{
    CardNumberLength = Convert.ToString(GetCardNumber()).Length;

    CardPINLength = Convert.ToString(GetCardPIN()).Length;

    CardNameHasSpace = GetCardName().IndexOf(" ");
}

CodePudding user response:

You could just return the boolean result:

return CardNumberLength == 16 && CardPINLength == 3 && CardNameHasSpace >= 0;

CodePudding user response:

If you absolutely had to do this without if tests, you could mash them together in a return statement. It's just a different syntax to express the same logic. I probably wouldn't suggest doing this without if tests though.

public bool Validate()
{
    return Convert.ToString(GetCardNumber()).Length == 16 //replaces CardNumberLength
        && Convert.ToString(GetCardPin()).Length == 3 // replaces CardPINLength
        && GetCardName().IndexOf(" ") < 1; // replaces CardNameHasSpace
}

CodePudding user response:

    public bool Validate()
    {

        string CardNumberLength = GetCardNumber().ToString().Length;
        string CardPINLength = GetCardPIN().ToString().Length;
        bool CardNameHasSpace = GetCardName().Contains(" ");
        
        return CardNumberLength == 16 && CardPINLength == 3 && !CardNameHasSpace
    }

using the .ToString() on an object is way better than Convert.ToString(), also you can check inside a string if it contains a certain string with the .Contains(string) function on a string.

CodePudding user response:

public bool Validate()
{
    CardNumberLength = Convert.ToString(GetCardNumber()).Length;
    CardPINLength = Convert.ToString(GetCardPIN()).Length;
    CardNameHasSpace = GetCardName().IndexOf(" ");

    return CardNumberLength == 16 && CardPINLength == 3 && CardNameHasSpace > -1;
}

Or

public bool Validate()
{
   CardNumberLength = Convert.ToString(GetCardNumber()).Length;
   CardPINLength = Convert.ToString(GetCardPIN()).Length;
   CardNameHasSpace = GetCardName().IndexOf(" ");

   if (CardNumberLength != 16)
      return false;
      
   if (CardPINLength != 3)
      return false;
      
   if (CardNameHasSpace == -1)
      return false;
  
   return true;
}

Perhaps, this helps you :)

  •  Tags:  
  • c#
  • Related