Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading