I've tried to execute a simple code just to study the enumeration topic. Yet, I've faced this issue: "Not all code paths return a value". Here is the code:
namespace ConsoleAppTest
{
class Program
{
enum Seasons { Winter, Spring, Summer, Fall };
static void Main(string[] args)
{
WhichSeason(3);
}
static Seasons WhichSeason(int month)
{
if (month >= 1 || month <= 3)
{
return Seasons.Winter;
}
else if (month >= 4 || month <= 6)
{
return Seasons.Spring;
}
else if (month >= 7 || month <= 9)
{
return Seasons.Summer;
}
else if (month >= 10 || month <= 12)
{
return Seasons.Fall;
}
}
}
}
I wonder what could cause this problem. Thanks :)
You should handle the else case. Your month integer could also be <1 or >12.
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
{
return Seasons.Winter;
}
else if (month >= 4 && month <= 6)
{
return Seasons.Spring;
}
else if (month >= 7 && month <= 9)
{
return Seasons.Summer;
}
else if (month >= 10 && month <= 12)
{
return Seasons.Fall;
}
else
{
throw new ArgumentOutOfRangeException("invalid month");
}
}
so if you call
WhichSeason(13); //throws exception
What should be returned if month, say -1 or 123? You can solve the problem in two main ways, silent:
// Please, notice "None"
enum Seasons { None, Winter, Spring, Summer, Fall };
static void Main(string[] args)
{
WhichSeason(3);
}
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
return Seasons.Winter;
else if (month >= 4 && month <= 6)
return Seasons.Spring;
else if (month >= 7 && month <= 9)
return Seasons.Summer;
else if (month >= 10 && month <= 12)
return Seasons.Fall;
else
return Seasons.None;
}
Or throwing appropriate exception, ArgumentOutOfRangeException in the case
enum Seasons { Winter, Spring, Summer, Fall };
static void Main(string[] args)
{
WhichSeason(3);
}
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 3)
return Seasons.Winter;
else if (month >= 4 && month <= 6)
return Seasons.Spring;
else if (month >= 7 && month <= 9)
return Seasons.Summer;
else if (month >= 10 && month <= 12)
return Seasons.Fall;
else
throw new ArgumentOutOfRangeException(
"month",
"month must be in [1..12] range."); // Exception
}
Edit: I've preserved WhichSeason intact, but it seems that you have a logic error in the implementation and the right routine should be
static Seasons WhichSeason(int month)
{
if (month >= 1 && month <= 2 || month == 12) // Jan, Feb and Dec
return Seasons.Winter;
else if (month >= 3 && month <= 5) // Mar-May
return Seasons.Spring;
else if (month >= 6 && month <= 8) // Jun-Aug
return Seasons.Summer;
else if (month >= 9 && month <= 11) // Sep-Nov
return Seasons.Fall;
else
return Seasons.None;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With