Home > Mobile >  Why can't i convert from string to integer here?
Why can't i convert from string to integer here?

Time:11-13

The code is:

public static bool IsValidIp(string ipAddres)
{
  string[] sNumbers = ipAddres.Split('.');
  int[] iNumbers = new int[sNumbers.Length];

  for(int i = 0; sNumbers.Length > i; i  ){
    iNumbers[i] = Convert.ToInt32(sNumbers[i]);
  }

  return 255 >= iNumbers.Max();
}

The error:

System.FormatException : Input string was not in a correct format.

I tried with several inputs like: "0.0.0.0", "12.255.56.1", "137.255.156.100". It keeps throwing back the same error message.

CodePudding user response:

Instead of Convert.ToInt32, Int32.TryParse might be a better solution, as it checks if input is valid before doing the conversion.

if (int.TryParse(sNumbers[i], out int result))
{
   iNumbers[i] = result;
}
else 
{
   return false;
}

However, I think you are trying to validate if specified argument is a valid IP address or not. Using IPAddress.TryParse method instead would be a better practice.

using System.Net;
// ...

public static bool IsValidIp(string address)
{
   return IPAddress.TryParse(address, out var _);
}

out var _ discards the value as it is not used.

  • Related