Add Your Heading Text Here

Enums or say enumerations are special kind of class used to represent the group of named constants.

An enum is declared using enum keyword.

Enum can’t be instantiated.

Enum Syntax :

enum enumName{

//named contact list separated with “,”

}

Enum class has some default methods and properties.

Each value in enum list can be retrieved using values method while, position of any enum constant can be retrieved using index property.

For ex :

enum ApiResponseCode { 
// list of named constants separated using “,”
   STATUS_CODE_200, 
   STATUS_CODE_400, 
   STATUS_CODE_500
}  
void main(){
  print(ApiResponseCode.values);
  print(ApiResponseCode.STATUS_CODE_500);
  print(ApiResponseCode.STATUS_CODE_200.index);
}

Output :

[ApiResponseCode.STATUS_CODE_200, ApiResponseCode.STATUS_CODE_400,
ApiResponseCode.STATUS_CODE_500]
ApiResponseCode.STATUS_CODE_500
0

Enum constants have zero based index starting from 0, 1, 2,…

Enums can be efficiently used in switch case to check corresponding values regarding different cases.

For ex :

enum Result { 
   PASS, 
   FAIL
}  
void main(){
  var result=Result.PASS;
  
  switch(result){
    case Result.PASS:
      print("Student Pass!!");
      break;
    case Result.FAIL:
      print("Student Fail!!");
      break;
  }
}

Output :

Student Pass!!

In this way, you can use enum for different case as per your requirements to optimise your code.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Show Buttons
Hide Buttons