1

Im doing a phone validation for 2 brands and both validation have almost the same meaning only different digits.

        if (!MobileFormat(num, brand,currency))
        {
            if (brand.Equals(Brand.LED.ToString()))
            {
                key = "The number of phone numbers must be "9" digits.";
            }
            else
            {
                key = "The number of phone numbers must be "10" digits.";
            }

        }

i expect the key to be in single line and not double and only change the digit.

ethan
  • 11
  • 4
  • Why not use a ternary operator if you have only if and else? – G_S Apr 10 '19 at 03:47
  • The first `if` statement is ok as for the second one you can use [Ternary Operators](https://stackoverflow.com/questions/3312786/benefits-of-using-the-conditional-ternary-operator). and as for you it would look something like `key = brand.Equals(Brand.LED.ToString()) ? "The number of phone numbers must be "9" digits." : "The number of phone numbers must be "10" digits.";` – vikscool Apr 10 '19 at 03:51

3 Answers3

2

try below:

key = string.Format("The number of phone numbers must be {0} digits.", brand.Equals(Brand.LED.ToString()) ? 9 : 10);
Rex
  • 2,130
  • 11
  • 12
1

Just capture digit value before building a string.

if (!MobileFormat(num, brand, currency))
{
    var digits = brand.Equals(Brand.LED.ToString()) ? 9 : 10;
    key = $"The number of phone numbers must be '{digits}' digits.";
}

With two lines you quickly recognise that two operations involved and saves some horizontal space.

Fabio
  • 31,528
  • 4
  • 33
  • 72
1

If either string is nullable, then can do this:

if (!MobileFormat(num, brand, currency))
     key = $"The number of phone numbers must be {(Equals(brand, Brand.LED.ToString()) ? 9 : 10)} digits";
Gauravsa
  • 6,330
  • 2
  • 21
  • 30