• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Is It Possible to Have Switch Case Without a Default?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
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);
}

}
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.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу