✅ Compiler limitation or is this logic wrong?

int state = 0;
switch (input.AsSpan(input.Length - 2, 2)) {
case "KB": format = MemoryFormatType.KiloByte1024; break;
case "MB": format = MemoryFormatType.MegaByte1024; break;
case "GB": format = MemoryFormatType.GigaByte1024; break;
case "TB": format = MemoryFormatType.TeraByte1024; break;
default: state = 1; break;
}
if (state == 0) {
return true;
}
int state = 0;
switch (input.AsSpan(input.Length - 2, 2)) {
case "KB": format = MemoryFormatType.KiloByte1024; break;
case "MB": format = MemoryFormatType.MegaByte1024; break;
case "GB": format = MemoryFormatType.GigaByte1024; break;
case "TB": format = MemoryFormatType.TeraByte1024; break;
default: state = 1; break;
}
if (state == 0) {
return true;
}
I'd expect the return true statement to work but I get "Parameter 'format' must be assigned upon exit". The method returns bool and has an out parameter called format.
4 Replies
bighugemassive3
bighugemassive3OP2w ago
Oh turns out I can just use goto instead of states... that helps
lycian
lycian2w ago
you could also do
format = input.AsSpan(input.Length - 2, 2) switch
{
"KB" => MemoryFormatType.KiloByte1024,
"MB" => MemoryFormatType.GigaByte1024,
"TB" => MemoryFormatType.TeraByte1024
_ => null
};

return format is not null;
format = input.AsSpan(input.Length - 2, 2) switch
{
"KB" => MemoryFormatType.KiloByte1024,
"MB" => MemoryFormatType.GigaByte1024,
"TB" => MemoryFormatType.TeraByte1024
_ => null
};

return format is not null;
Angius
Angius2w ago
Certainly better than a goto
lycian
lycian2w ago
fixed my bad syntax, but yea goto is a bit clunky
Want results from more Discord servers?
Add your server