DEV Community

boomi1
boomi1

Posted on

Is It Possible to Have Switch Case Without a Default?

I came across this question while working with switch-case statements and I realised that the answer is both YES AND NO.

The necessity of a default case depends on where and how you're using the switch. If it's used inside a function that returns a value, then having a default case becomes necessary in certain situations. Otherwise, it's not mandatory.

Let’s break this down with two scenarios:

Scenario 1:

using System;
public class Program
{
public int Number(int num)
{
switch(num)
{
case 1: return 1;
case 2: return 2;
default: return -1;
}
}
public static void Main(string[] args)
{
Program p = new Program();
int result = p.Number(9);
Console.WriteLine(result);
}
}
In the above code, we’re returning a value from the function using a switch statement. If none of the case values match, it falls back to the default case and returns -1.

Now, if we remove the default case, the compiler will throw an error:

"Not all code paths return a value"

This is because there's a possibility that no case matches, and the function would have no return path in that situation. Hence, in such scenarios, a default case is necessary to ensure all paths return a value

Scenario 2:

public class Program
{
public void Number(int num)
{
switch(num)
{
case 1 :
Console.WriteLine("One");
case 2 :
Console.WriteLine("Two");

}
}

public static void Main(string[] args)
{

   Program p = new Program();
   int result = p.Number(9);
   Console.WriteLine(result);
}
Enter fullscreen mode Exit fullscreen mode

}
In this case, the function has a void return type, meaning it doesn’t return any value. If none of the cases match, the control simply exits the switch block and continues execution. Here, not having a default case is completely valid—though it might not be ideal for readability or handling unexpected input.

Conclusion:

Whether or not to include a default case depends on the scenario, especially when it involves return values.

However, as a best practice, it’s always recommended to include a default case. It improves code readability, helps with debugging, and ensures you handle all unexpected input gracefully.

Top comments (1)

Collapse
 
magegs profile image
magegs

Nice Explanation