Question
Answer and Explanation
Printing the enum of a value depends on the programming language you are using. Here are some examples for different languages:
Python:
In Python, you can use the enum
module to define enumerations. To print the enum value, you can simply access the name
attribute of the enum member.
import enum
class Color(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3
color = Color.RED
print(color.name) # Output: RED
print(color.value) # Output: 1
Java:
In Java, Enums are a special data type. You can print an enum's name using the name()
method.
public enum Color {
RED, GREEN, BLUE;
}
public class Main {
public static void main(String[] args) {
Color color = Color.RED;
System.out.println(color.name()); // Output: RED
System.out.println(color.toString()); // Output: RED
System.out.println(color.ordinal()); // Output: 0
}
}
JavaScript:
JavaScript doesn't have a built-in enum type, but you can simulate it using objects. Printing the enum value involves accessing the appropriate property.
const Color = {
RED: "Red",
GREEN: "Green",
BLUE: "Blue"
};
const color = Color.RED;
console.log(color); // Output: Red
TypeScript:
Typescript supports enums. You can print the enum value directly.
enum Color {
Red,
Green,
Blue
}
let color: Color = Color.Red;
console.log(Color[color]); //Output: Red
console.log(color); //Output: 0
C#:
In C#, Enums are supported and printing the enum value's name is straightforward using ToString()
method.
enum Color {
Red,
Green,
Blue
}
Color color = Color.Red;
Console.WriteLine(color.ToString()); //Output: Red
Console.WriteLine((int)color); //Output: 0
The specific method for printing the enum name varies, but the core principle remains consistent: you need to access the name or string representation associated with the enum value.