How to check if enum value is valid?
enum
value is valid in C++ if it falls in range [A, B], which is defined by the standard rule below. So in case of enum X { A = 1, B = 3 }
, the value of 2
is considered a valid enum value.
Consider 7.2/6 of standard:
For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax. It is possible to define an enumeration that has values not defined by any of its enumerators.
There is no retrospection in C++. One approach to take is to list enum values in an array additionally and write a wrapper that would do conversion and possibly throw an exception on failure.
See Similar Question about how to cast int to enum for further details.
Is there a way to check if int is legal enum in C#?
Check out Enum.IsDefined
Usage:
if(Enum.IsDefined(typeof(MyEnum), value))
MyEnum a = (MyEnum)value;
This is the example from that page:
using System;
[Flags] public enum PetType
{
None = 0, Dog = 1, Cat = 2, Rodent = 4, Bird = 8, Reptile = 16, Other = 32
};
public class Example
{
public static void Main()
{
object value;
// Call IsDefined with underlying integral value of member.
value = 1;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with invalid underlying integral value.
value = 64;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with string containing member name.
value = "Rodent";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with a variable of type PetType.
value = PetType.Dog;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = PetType.Dog | PetType.Cat;
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with uppercase member name.
value = "None";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = "NONE";
Console.WriteLine("{0}: {1}", value, Enum.IsDefined(typeof(PetType), value));
// Call IsDefined with combined value
value = PetType.Dog | PetType.Bird;
Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
value = value.ToString();
Console.WriteLine("{0:D}: {1}", value, Enum.IsDefined(typeof(PetType), value));
}
}
The example displays the following output:
// 1: True
// 64: False
// Rodent: True
// Dog: True
// Dog, Cat: False
// None: True
// NONE: False
// 9: False
// Dog, Bird: False
How to check if an enum variable is valid?
A common convention for this is to do something like this:
typedef enum {
typeA,
typeB,
typeC,
num_types
} myenum_t;
Then you can check for (t < num_types)
.
If you subsequently add more enums, e.g.
typedef enum {
typeA,
typeB,
typeC,
typeD,
typeE,
num_types
} myenum_t;
then num_types
is automatically updated and your error checking code doesn't need to change.
Validate Enum Values
You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!
IsDefined
is fine for most scenarios, you could start with:
public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)
{
retVal = default(TEnum);
bool success = Enum.IsDefined(typeof(TEnum), enumValue);
if (success)
{
retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);
}
return success;
}
(Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension)
Check if value exists in enum in TypeScript
If you want this to work with string enums, you need to use Object.values(ENUM).includes(ENUM.value)
because string enums are not reverse mapped, according to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:
enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}
becomes:
{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}
So you just need to do:
if (Object.values(Vehicle).includes('car')) {
// Do stuff here
}
If you get an error for: Property 'values' does not exist on type 'ObjectConstructor'
, then you are not targeting ES2017. You can either use this tsconfig.json config:
"compilerOptions": {
"lib": ["es2017"]
}
Or you can just do an any cast:
if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}
How to check If a Enum contain a number?
The IsDefined
method requires two parameters. The first parameter is the type of the enumeration to be checked. This type is usually obtained using a typeof expression. The second parameter is defined as a basic object. It is used to specify either the integer value or a string containing the name of the constant to find. The return value is a Boolean that is true if the value exists and false if it does not.
enum Status
{
OK = 0,
Warning = 64,
Error = 256
}
static void Main(string[] args)
{
bool exists;
// Testing for Integer Values
exists = Enum.IsDefined(typeof(Status), 0); // exists = true
exists = Enum.IsDefined(typeof(Status), 1); // exists = false
// Testing for Constant Names
exists = Enum.IsDefined(typeof(Status), "OK"); // exists = true
exists = Enum.IsDefined(typeof(Status), "NotOK"); // exists = false
}
SOURCE
Check if PHP enum contains case, like try() method on basic (not backed) enumerations
You can use the static method cases()
for this. This returns an array of all values in the enum. The values have a "name" property that is a string representation you can check against (backed enums also have a "value" property that contains the string value you defined in the enum).
So an example implementation could be something like:
enum Fruit {
case APPLE;
case ORANGE;
case BANANA;
}
// String from user input
$fruit = $_POST['fruit'];
// Find matching fruit in all enum cases
$fruits = Fruit::cases();
$matchingFruitIndex = array_search($fruit, array_column($fruits, "name"));
// If found, eat it
if ($matchingFruitIndex !== false) {
$matchingFruit = $fruits[$matchingFruitIndex];
eatFruit($matchingFruit);
} else {
echo $fruit . " is not a valid Fruit";
}
function eatFruit(Fruit $fruit): void {
if ($fruit === Fruit::APPLE) {
echo "An apple a day keeps the doctor away";
} elseif ($fruit === Fruit::ORANGE) {
echo "When life gives you oranges, make orange juice";
} elseif ($fruit === Fruit::BANANA) {
echo "Banana for scale";
}
}
Working version with sample data: https://3v4l.org/ObD3s
If you want to do this more often with different enums, you could write a helper function for this:
function getEnumValue($value, $enumClass) {
$cases = $enumClass::cases();
$index = array_search($value, array_column($cases, "name"));
if ($index !== false) {
return $cases[$index];
}
return null;
}
$fruit = getEnumValue($_POST['fruit'], Fruit::class);
if ($fruit !== null) {
eatFruit($fruit);
} else {
echo $_POST['fruit'] . " is not a valid Fruit";
}
Example with the same sample data: https://3v4l.org/bL8Wa
Related Topics
Linker Error When Calling a C Function from C++ Code in Different VS2010 Project
How Can a C++ Header File Include Implementation
How to Check If an Object's Type Is a Particular Subclass in C++
C++11 Initializer List Fails - But Only on Lists of Length 2
How to Recover View Space Position Given View Space Depth Value and Ndc Xy
Are Multiple Mutations Within Initializer Lists Undefined Behavior
Global Scope VS Global Namespace
Why Isn't the [] Operator Const for Stl Maps
What Do Compilers Do with Compile-Time Branching
Is Accessing Data in the Heap Faster Than from the Stack
Which C++ Standard Is the Default When Compiling with G++
😃 (And Other Unicode Characters) in Identifiers Not Allowed by G++
Passing a Variable as a Template Argument