0

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(" ");
}
EKOlog
  • 410
  • 7
  • 19

4 Answers4

5

You could just return the boolean result:

return CardNumberLength == 16 && CardPINLength == 3 && CardNameHasSpace >= 0;
Jan Köhler
  • 5,817
  • 5
  • 26
  • 35
  • My apologies, i should have said that i want it to check all 3 of these values, and if they are all correct (as listed in the description), i want it to return "true", if not, "false". – Alex Gottschalk Nov 03 '21 at 20:23
  • 3
    Exactly this happens in that statement :) Please note that `=` is an assignment and `==` is a comparison. – Jan Köhler Nov 03 '21 at 20:26
1

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
}
Dortimer
  • 619
  • 8
  • 25
-1
    public bool Validate()
    {
        int CardNumberLength = int.Parse(GetCardNumber().ToString().Length);
        int CardPINLength = int.Parse(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.

GHOST
  • 337
  • 3
  • 9
-3
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 :)

Pasan Ratnayake
  • 495
  • 4
  • 10