Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
keyword
communitycreator
case

What is the case keyword in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The case keyword is used in a switch statement. Each case expression must be unique. A case only takes a constant value.

Note: A case cannot be a variable or expression.

Syntax

switch(variable_expression) { 
   case constant_expr1: { 
      // statements; 
   } 
   break; 
  case constant_expr2: { 
      // statements; 
   }
   default: { 
      //statements;  
   }
   break; 
} 

Example

The following code shows how to use the case keyword in Dart.

// dart program
void main()
{
    int num = 3;
    switch (num) {
    case 1: {
        print("Shot 1");
    } break;
    case 3: {
        print("Shot 3");
    } break;
    default: {
        print("This is default case");
    } break;
    }
}

Explanation

  • Lines 2–16: We create the main() function.
  • Line 4: We declare a variable num of type int and assign a value to it.
  • Lines 5–15: We use a switch statement. The value of the num is tested against the different cases in the switch. If the value of num matches one of the cases, the corresponding code block is executed. Otherwise, the code within the default block is executed.

Note: Each case must be unique.

RELATED TAGS

dart
keyword
communitycreator
case

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring