I have a method to validate a parameter IP Address. Being new to development as a whole I would like to know if there is a better way of doing this.
using System.Net;
public static bool CheckIPValid(string strIP)
{
IPAddress result = null;
return
!String.IsNullOrEmpty(strIP) &&
IPAddress.TryParse(strIP, out result);
}
and you're done
Edit 1
Added some additional checks to prevent exceptions being thrown (which are costly). PS it won't handle unicode.
Edit 2
@StephenMurby IPAddress.TryParse will return true if it successfully parsed the string. If you check the documentation for the method though it will throw an exception in two cases.
Its up to you to decide (design decision) whether you want to throw exceptions or return false. When it comes to parsing I generally prefer to return false rather than exceptions (the assumption being this is input that's not guaranteed to be correct).
Breaking the return statement down, I am saying,
Remember C# boolean expressions are lazy evaluated, so the CLR won't attempt to even parse the string if it is null or empty.
About the missing if, you can do something like,
if (IP.TryParse(strIP, out result)
{
return true;
}
But all you really doing is saying if something is true, return true. Easier to just return the expression straight away.