I have a method like so:
public static long? FromIpv4ToLong(this string ipAddress)
{
var octets = ipAddress.Split(IpSplitChar);
if (octets.Length != 4) return null;
var success = long.TryParse(octets[0], out long a)
&& long.TryParse(octets[1], out long b)
&& long.TryParse(octets[2], out long c)
&& long.TryParse(octets[3], out long d);
if (!success) return null;
return ((16777216L * a) + (65536L * b) + (256L * c) + d);
}
...now, the variables a
, b
, c
, and d
will never be "unassigned" by the point where they would be referenced, but the compiler doesn't see it that way. Is there a way I can force the compiler to just "build it anyway"? It seems silly to initialize these values ahead of time.
Just refactor the code to avoid the pointless local variable that's confusing things, taking advantage of the fact that within the if
body, the compiler does know that everything is definitely assigned:
public static long? FromIpv4ToLong(this string ipAddress)
{
var octets = ipAddress.Split(IpSplitChar);
if (octets.Length != 4) return null;
if (long.TryParse(octets[0], out long a)
&& long.TryParse(octets[1], out long b)
&& long.TryParse(octets[2], out long c)
&& long.TryParse(octets[3], out long d)
{
return (16777216L * a) + (65536L * b) + (256L * c) + d;
}
return null;
}
Or using a conditional operator (and using shifting for simplicity):
public static long? FromIpv4ToLong(this string ipAddress)
{
var octets = ipAddress.Split(IpSplitChar);
return octets.Length == 4
&& long.TryParse(octets[0], out long a)
&& long.TryParse(octets[1], out long b)
&& long.TryParse(octets[2], out long c)
&& long.TryParse(octets[3], out long d)
? (a << 24) | (b << 16) + (c << 8) | d
: null;
}
See more on this question at Stackoverflow