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 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 that integer type belongs to enum member
Use Enum.IsDefined
Enum.IsDefined(typeof(Enum1), 4) == true
but
Enum.IsDefined(typeof(Enum1), 1) == false
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 enum is in one of desired states
Bitwise logic should work on flag enums like this.
if((Flow & (GameFlow.Normal | GameFlow.NormalNoMove)) > 0)
It's also possible to create enum values that combine other values, as I mention here.
So, in your case:
[Flags]
public enum GameFlow
{
Normal = 1,
NormalNoMove = 2,
Paused = 4,
Battle = 8,
AnyNormal = Normal | NormalNoMove
}
bool IsNormal(GameFlow flow)
{
return (flow & GameFlow.AnyNormal) > 0;
}
And a LINQPad test:
void Main()
{
IsNormal(GameFlow.Normal).Dump();// True
IsNormal(GameFlow.NormalNoMove).Dump();// True
IsNormal(GameFlow.Paused).Dump();// False
IsNormal(GameFlow.Battle).Dump();// False
IsNormal(GameFlow.Normal | GameFlow.Paused).Dump();// True
IsNormal(GameFlow.NormalNoMove | GameFlow.Battle).Dump();// True
IsNormal(GameFlow.Paused | GameFlow.Battle).Dump();// False
IsNormal(GameFlow.Battle | GameFlow.Normal).Dump();// True
}
Based on your comment, I'm wondering if you should revise the bitwise flags here, too. It sounds like "Normal" is a state you want to check for, and "NormalNoMove" builds on that. Maybe your enum should look more like this:
[Flags]
public enum GameFlow
{
Normal = 1,
NormalNoMove = Normal | 2,
Paused = 4,
Battle = 8
}
That way, you can check whether flow & GameFlow.Normal > 0
to see if you're in either normal state: NormalNoMove
just "extends" Normal
, so to speak.
How to effectively validate an integer that represents a flagged enumeration?
- compute a cumulative bitwise "or" over all legal values (perhaps using Enum.GetValues)
- compute "testValue & ~allValues"
- if that is non-zero, then it is impossible to form your current value by combining the legal flags
Get int value from enum in C#
Just cast the enum, e.g.
int something = (int) Question.Role;
The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int
.
However, as cecilphillip points out, enums can have different underlying types.
If an enum is declared as a uint
, long
, or ulong
, it should be cast to the type of the enum; e.g. for
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
you should use
long something = (long)StarsInMilkyWay.Wolf424B;
Check is the input in Enum
You can use the GetName
method to get the name of the enum value associated with its underlying value (there are other methods too, see this post). You only need one foreach
loop, and you can use string interpolation to print in the format value = name
:
foreach (int rawValue in Enum.GetValues(typeof(Automerkit))) {
WriteLine($"{rawValue} = {Enum.GetName(typeof(Automerkit), rawValue)}");
}
Related Topics
Groupby on Complex Object (E.G. List<T>)
How to Set Dynamic Value in My Attribute
Detect If Geolocation Is in Complex Polygon or Not
How to Get the Access Token from a Blazor (Server-Side) Web App
Itextsharp: Adjust 2 Elements on Exactly One Page
What Are C# Lambda's Compiled Into? a Stackframe, an Instance of an Anonymous Type, Or
Data Contract Serializer - How to Omit the Outer Element of a Collection
Stop SQL Query Execution from .Net Code
C#: HTMLagilitypack Extract Inner Text
Install to Same Path When Upgrading Application
Ftpwebrequest Ftp Download with Progressbar
Reading Emails from Gmail in C#
How to Check If System.Net.Webclient.Downloaddata Is Downloading a Binary File
Should I Worry About "This Async Method Lacks 'Await' Operators and Will Run Synchronously" Warning
How to Put a Usercontrol into Visual Studio Toolbox
Adding Scripting Functionality to .Net Applications
How to Restrict Access to Nested Class Member to Enclosing Class