Why can't I define a bit in c#? - c#

Why isn't there a bit structure in C#?

For what's worth, here is a full-fledged bit structure, complete with int and bool casting and arithmetic operations. Probably not perfect, but works fine for me. Enjoy!
/// <summary>
/// Represents a single bit that can be implicitly cast to/from and compared
/// with booleans and integers.
/// </summary>
/// <remarks>
/// <para>
/// An instance with a value of one is equal to any non-zero integer and is true,
/// an instance with a value of zero is equal to the integer zero and is false.
/// </para>
/// <para>
/// Arithmetic and logical AND, OR and NOT, as well as arithmetic XOR, are supported.
/// </para>
/// </remarks>
public struct Bit
{
/// <summary>
/// Creates a new instance with the specified value.
/// </summary>
/// <param name="value"></param>
public Bit(int value) : this()
{
Value = value == 0 ? 0 : 1;
}
/// <summary>
/// Gets the value of the bit, 0 or 1.
/// </summary>
public int Value { get; private set; }
#region Implicit conversions
public static implicit operator Bit(int value)
{
return new Bit(value);
}
public static implicit operator int(Bit value)
{
return value.Value;
}
public static implicit operator bool(Bit value)
{
return value.Value == 1;
}
public static implicit operator Bit(bool value)
{
return new Bit(value ? 1 : 0);
}
#endregion
#region Arithmetic operators
public static Bit operator |(Bit value1, Bit value2)
{
return value1.Value | value2.Value;
}
public static Bit operator &(Bit value1, Bit value2)
{
return value1.Value & value2.Value;
}
public static Bit operator ^(Bit value1, Bit value2)
{
return value1.Value ^ value2.Value;
}
public static Bit operator ~(Bit value)
{
return new Bit(value.Value ^ 1);
}
public static Bit operator !(Bit value)
{
return ~value;
}
#endregion
#region The true and false operators
public static bool operator true(Bit value)
{
return value.Value == 1;
}
public static bool operator false(Bit value)
{
return value.Value == 0;
}
#endregion
#region Comparison operators
public static bool operator ==(Bit bitValue, int intValue)
{
return
(bitValue.Value == 0 && intValue == 0) ||
(bitValue.Value == 1 && intValue != 0);
}
public static bool operator !=(Bit bitValue, int intValue)
{
return !(bitValue == intValue);
}
public override bool Equals(object obj)
{
if(obj is int)
return this == (int)obj;
else
return base.Equals(obj);
}
#endregion
}

It is called a boolean. At least, it would serve the basic function, right? You don't twiddle bits that often in C# (at least, I don't), and if you need to you can use the built in operations.

There is a BitArray class..

What would you want to do with it? Bear in mind that the CLR isn't going to try to pack multiple variables into a byte, so having one on its own would be no more useful than boolean. If you wanted to have a collection of them - well, that's what BitArray is for, as David pointed out.
If we did have a Bit structure, I suspect people would expect multiple Bit variables to be packed efficiently in memory - by not having the type in the first place, we avoid that expectation and lead people towards other solutions such as BitArray.

If you have a collection of bit flags, then using enums (with falgs attribute) and integers work a long way.

Though maybe there are rare exceptions, computers are not designed or intended to manipulate or allocate individual bits. Even at the lowest levels (assembly or pure machine language), you will not be able to allocate or access an individual bit. You have the same tools available in this regard as you have from any programming level: bytes and bitwise operations.

Along with the BitArray class already mentioned there is a also the more efficient BitVector32 Structure.
BitVector32 is more efficient than BitArray for Boolean values and
small integers that are used internally. A BitArray can grow
indefinitely as needed, but it has the memory and performance overhead
that a class instance requires. In contrast, a BitVector32 uses only
32 bits.
Keep in mind you are limited to 32 values.
Examples of BitVector32 usage at Dotnetpearls.com

You can do this now in C# 7.0!
public const int One = 0b0001;
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#numeric-literal-syntax-improvements

Related

C# unsigned decimal implementation [duplicate]

I need to use an unsigned double but it turns out C# does not provide such a type.
Does anyone know why?
As pointed out by Anders Forsgren, there is no unsigned doubles in the IEEE spec (and therefore not in C#).
You can always get the positive value by calling Math.Abs() and you could wrap a double in a struct and enforce the constraint there:
public struct PositiveDouble
{
private double _value;
public PositiveDouble() {}
public PositiveDouble(double val)
{
// or truncate/take Abs value automatically?
if (val < 0)
throw new ArgumentException("Value needs to be positive");
_value = val;
}
// This conversion is safe, we can make it implicit
public static implicit operator double(PositiveDouble d)
{
return d._value;
}
// This conversion is not always safe, so we make it explicit
public static explicit operator PositiveDouble(double d)
{
// or truncate/take Abs value automatically?
if (d < 0)
throw new ArgumentOutOfRangeException("Only positive values allowed");
return new PositiveDouble(d);
}
// add more cast operators if needed
}
Floating point numbers are simply the implementation of the IEEE 754 spec. There is no such thing as an unsigned double there as far as i know.
http://en.wikipedia.org/wiki/IEEE_754-2008
Why do you need an unsigned floating point number?
There is no such thing as an unsigned double in any language or system that I have ever heard of.
I need to give the ability to pass a variable that can be a fraction and must be positive. I wanted to use it in my Function signature to enforce it.
If you want to enforce a constraint that the parameter is positive, then you need to do that with a runtime check.
I rolled out a more detailed implementation of #Isak Savo's with tweaks here and there. Not sure if its perfect, but it's a great place to start.
public struct UDouble
{
/// <summary>
/// Equivalent to <see cref="double.Epsilon"/>.
/// </summary>
public static UDouble Epsilon = double.Epsilon;
/// <summary>
/// Represents the smallest possible value of <see cref="UDouble"/> (0).
/// </summary>
public static UDouble MinValue = 0d;
/// <summary>
/// Represents the largest possible value of <see cref="UDouble"/> (equivalent to <see cref="double.MaxValue"/>).
/// </summary>
public static UDouble MaxValue = double.MaxValue;
/// <summary>
/// Equivalent to <see cref="double.NaN"/>.
/// </summary>
public static UDouble NaN = double.NaN;
/// <summary>
/// Equivalent to <see cref="double.PositiveInfinity"/>.
/// </summary>
public static UDouble PositiveInfinity = double.PositiveInfinity;
double value;
public UDouble(double Value)
{
if (double.IsNegativeInfinity(Value))
throw new NotSupportedException();
value = Value < 0 ? 0 : Value;
}
public static implicit operator double(UDouble d)
{
return d.value;
}
public static implicit operator UDouble(double d)
{
return new UDouble(d);
}
public static bool operator <(UDouble a, UDouble b)
{
return a.value < b.value;
}
public static bool operator >(UDouble a, UDouble b)
{
return a.value > b.value;
}
public static bool operator ==(UDouble a, UDouble b)
{
return a.value == b.value;
}
public static bool operator !=(UDouble a, UDouble b)
{
return a.value != b.value;
}
public static bool operator <=(UDouble a, UDouble b)
{
return a.value <= b.value;
}
public static bool operator >=(UDouble a, UDouble b)
{
return a.value >= b.value;
}
public override bool Equals(object a)
{
return !(a is UDouble) ? false : this == (UDouble)a;
}
public override int GetHashCode()
{
return value.GetHashCode();
}
public override string ToString()
{
return value.ToString();
}
}
As to why one would need an unsigned double, consider that width and height dimensions of UI elements cannot be negative in most applications as that would be illogical; why, then, support negative numbers where they're not needed?
Some values like PositiveInfinity and NaN may still be applicable; therefore, we provide intuitive references to them. The big difference between double and UDouble is UDouble wouldn't need the constant NegativeInfinity (or at least I assume this much; I am not a mathematician, after all) and MinValue constant is simply 0. Also, Epsilon is positive, though, I am uncertain whether or not it is logical to use in the same context as unsigned numbers.
Note, this implementation automatically truncates negative numbers and an exception is thrown if you attempt to set to NegativeInfinity.

Using object references as keys in a Dictionary in C# [duplicate]

Is it possible to use an object as a key for a Dictonary<object, ...> in such a way that the Dictionary treats objects as equal only if they are identical?
For example, in the code below, I want Line 2 to return 11 instead of 12:
Dictionary<object, int> dict = new Dictionary<object, int>();
object a = new Uri("http://www.google.com");
object b = new Uri("http://www.google.com");
dict[a] = 11;
dict[b] = 12;
Console.WriteLine(a == b); // Line 1. Returns False, because a and b are different objects.
Console.WriteLine(dict[a]); // Line 2. Returns 12
Console.WriteLine(dict[b]); // Line 3. Returns 12
The current Dictionary implementation uses object.Equals() and object.GetHashCode() on the keys; but I am looking for a different kind of dictionary that uses the object's identity as a key (instead of the object's value). Is there such a Dictionary in .NET or do I have to implement it from scratch?
You don't need to build your own dictionary - you need to build your own implementation of IEqualityComparer<T> which uses identity for both hashing and equality. I don't think such a thing exists in the framework, but it's easy enough to build due to RuntimeHelpers.GetHashCode.
public sealed class IdentityEqualityComparer<T> : IEqualityComparer<T>
where T : class
{
public int GetHashCode(T value)
{
return RuntimeHelpers.GetHashCode(value);
}
public bool Equals(T left, T right)
{
return left == right; // Reference identity comparison
}
}
I've restricted T to be a reference type so that you'll end up with objects in the dictionary; if you used this for value types you could get some odd results. (I don't know offhand how that would work; I suspect it wouldn't.)
With that in place, the rest is easy. For example:
Dictionary<string, int> identityDictionary =
new Dictionary<string, int>(new IdentityEqualityComparer<string>());
Of course the other answers are entirely correct, but I wrote my own version to suit my needs:
/// <summary>
/// An equality comparer that compares objects for reference equality.
/// </summary>
/// <typeparam name="T">The type of objects to compare.</typeparam>
public sealed class ReferenceEqualityComparer<T> : IEqualityComparer<T>
where T : class
{
#region Predefined
private static readonly ReferenceEqualityComparer<T> instance
= new ReferenceEqualityComparer<T>();
/// <summary>
/// Gets the default instance of the
/// <see cref="ReferenceEqualityComparer{T}"/> class.
/// </summary>
/// <value>A <see cref="ReferenceEqualityComparer<T>"/> instance.</value>
public static ReferenceEqualityComparer<T> Instance
{
get { return instance; }
}
#endregion
/// <inheritdoc />
public bool Equals(T left, T right)
{
return Object.ReferenceEquals(left, right);
}
/// <inheritdoc />
public int GetHashCode(T value)
{
return RuntimeHelpers.GetHashCode(value);
}
}
Design rationale:
The class is sealed.
If the class is not designed to be extended, I'm going to avoid all that expense by sealing it.— Eric Lippert
I know many people (including myself) who believe that classes should indeed be sealed by default.— Jon Skeet
There is an Instance static read-only property to expose a single instance of this class.
It uses Object.ReferenceEquals() instead of == because ReferenceEquals is more explicit.
It uses RuntimeHelpers.GetHashCode() because I don't want to use the possibly overridden GetHashCode of the object, which may not match the behavior of ReferenceEquals. This also avoids a null-check.
It has documentation.
Use your own equality comparer
public class ObjectIdentityEqualityComparer : IEqualityComparer<object>
{
public int GetHashCode(object o)
{
return o.GetHashCode();
}
public bool Equals(object o1, object o2)
{
return object.ReferenceEquals(o1, o2);
}
}
Note that GetHashCode can be overridden, but the crucial check is made with Equals.
As of 5.0, ReferenceEqualityComparer now ships with the runtime.
Use Dictionary with IEqualityComparer<TKey> comparer

Class to calculate hash codes in GetHashCode

I use an XOR based implementation in the GetHashCode implementation of most of my equatable types.
I've read several posts explaining why it is not the best solution so I decided to implement GetHashCode as suggested by Jon Skeet:
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
Since the code is likely to be similar in most implementations, I tried to build a helper class to calculate hash codes for all my classes. It should be an easy thing to do but one of the main constraints with GetHashCode is it has to be fast. Therefore any implementation involving allocation is probably a no go (for instance, the use of a non static class).
Ideally a call to such a method would look like:
public override GetHashCode() => HashCodeCalculator.Calculate(X, Y, Z);
And have all the logic (unchecked + primes + null check...). But the use of a params parameter implicitly creates an array.
Is it best to duplicate the hashing algorithm in each class instead? Or is a class like the following as efficient?
public static class HashCalculator
{
private const int _seed = 5923;
private const int _multiplier = 7481;
public static int Add(object value) => Add(_seed, value);
public static int Add(int current, object value)
{
int valueHashCode = (value != null) ? value.GetHashCode() : 0;
unchecked
{
return (current * _multiplier) + valueHashCode;
}
}
}
which can then be used like this:
public override int GetHashCode()
{
int result = HashCalculator.Add(Prop1);
result = HashCalculator.Add(result, Prop2);
return result;
}
You can create overloads for various small fixed numbers of parameters (2, 3, 4, etc. until you decide to stop), in order to avoid the array allocation, and then have a params overload that only ever needs to be used when there is a particularly large number of operands, at which point the overhead of the array allocation is less likely to be a problem (as it'll be a smaller percentage of the work done).
I can see why it is so tempting to have some kind of helper tool to calc hashes, but in this case efficiency is in great contradiction to convenience. You are trying to have a cookie and eat it and the answer depends on how much cookie you are willing to left over :)
One additional method call? Then it should have signature simmilar to
int HashCode(params int subhashcodes)
but invoking it will be ugly because you need to provide hashcodes of fields as parameters.
One method call and boxing? Then you can change int to object in previous signature to call fields hashcodes inside your method (I'm not fully sure that there will be no boxing in first case - feel free to correct me)
Personally I will stick to writing it by hand (or by Resharper).
After benchmarking it appears that using a struct like the following is almost as efficient as XORing and nicely encapsulates hash codes calculation.
/// <summary>
/// Calculates a hash code based on multiple hash codes.
/// </summary>
public struct HashCode
{
private const int _seed = 5923;
private const int _multiplier = 7481;
/// <summary>
/// Builds a new hash code.
/// </summary>
/// <returns>The built hash code.</returns>
public static HashCode Build() => new HashCode(_seed);
/// <summary>
/// Constructor from a hash value.
/// </summary>
/// <param name="value">Hash value.</param>
private HashCode(int value)
{
_value = value;
}
/// <summary>
/// Builds a new hash code and initializes it from a hash code source.
/// </summary>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
public HashCode(object hashCodeSource)
{
int sourceHashCode = GetHashCode(hashCodeSource);
_value = AddValue(_seed, sourceHashCode);
}
private readonly int _value;
/// <summary>
/// Returns the hash code for a given hash code source (0 if the source is null).
/// </summary>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
/// <returns>The hash code.</returns>
private static int GetHashCode(object hashCodeSource) => (hashCodeSource != null) ? hashCodeSource.GetHashCode() : 0;
/// <summary>
/// Adds a new hash value to a hash code.
/// </summary>
/// <param name="currentValue">Current hash value.</param>
/// <param name="valueToAdd">Value to add.</param>
/// <returns>The new hash value.</returns>
private static int AddValue(int currentValue, int valueToAdd)
{
unchecked
{
return (currentValue * _multiplier) + valueToAdd;
}
}
/// <summary>
/// Adds an object's hash code.
/// </summary>
/// <param name="hashCode">Hash code to which the object's hash code has to be added.</param>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
/// <returns>The updated hash instance.</returns>
public static HashCode operator +(HashCode hashCode, object hashCodeSource)
{
int sourceHashCode = GetHashCode(hashCodeSource);
int newHashValue = AddValue(hashCode._value, sourceHashCode);
return new HashCode(newHashValue);
}
/// <summary>
/// Implicit cast operator to int.
/// </summary>
/// <param name="hashCode">Hash code to convert.</param>
public static implicit operator int(HashCode hashCode) => hashCode._value;
}
which can be used like this:
public override int GetHashCode() => new HashCode(Prop1) + Prop2;
EDIT:
.net core now has such a HashCode struct.

Extend Enum with flag methods?

I have found good examples on how to create extension methods to read out single values from bitwise enums. But now that C# 4 has added the HasFlag method they are really not needed.
What I think would be really helpful though is an extension to SET a single flag!
I have many situations where I need to set the flag values individually.
I want an extension method with this signature:
enumVariable.SetFlag(EnumType.SingleFlag, true);
OR possibly:
enumVariable.SetFlag<EnumType>(EnumType.SingleFlag, true);
Today I found a solution on http://hugoware.net/blog/enums-flags-and-csharp. Thanks Hugo! Excellent code that works fine. I adjusted it slightly and added it to my existing EnumExtender:
public static class EnumExtender
{
/// <summary>
/// Adds a flag value to enum.
/// Please note that enums are value types so you need to handle the RETURNED value from this method.
/// Example: myEnumVariable = myEnumVariable.AddFlag(CustomEnumType.Value1);
/// </summary>
public static T AddFlag<T>(this Enum type, T enumFlag)
{
try
{
return (T)(object)((int)(object)type|(int)(object)enumFlag);
}
catch(Exception ex)
{
throw new ArgumentException(string.Format("Could not append flag value {0} to enum {1}",enumFlag, typeof(T).Name), ex);
}
}
/// <summary>
/// Removes the flag value from enum.
/// Please note that enums are value types so you need to handle the RETURNED value from this method.
/// Example: myEnumVariable = myEnumVariable.RemoveFlag(CustomEnumType.Value1);
/// </summary>
public static T RemoveFlag<T>(this Enum type, T enumFlag)
{
try
{
return (T)(object)((int)(object)type & ~(int)(object)enumFlag);
}
catch (Exception ex)
{
throw new ArgumentException(string.Format("Could not remove flag value {0} from enum {1}", enumFlag, typeof(T).Name), ex);
}
}
/// <summary>
/// Sets flag state on enum.
/// Please note that enums are value types so you need to handle the RETURNED value from this method.
/// Example: myEnumVariable = myEnumVariable.SetFlag(CustomEnumType.Value1, true);
/// </summary>
public static T SetFlag<T>(this Enum type, T enumFlag, bool value)
{
return value ? type.AddFlag(enumFlag) : type.RemoveFlag(enumFlag);
}
/// <summary>
/// Checks if the flag value is identical to the provided enum.
/// </summary>
public static bool IsIdenticalFlag<T>(this Enum type, T enumFlag)
{
try
{
return (int)(object)type == (int)(object)enumFlag;
}
catch
{
return false;
}
}
/// <summary>
/// Convert provided enum type to list of values.
/// This is convenient when you need to iterate enum values.
/// </summary>
public static List<T> ToList<T>()
{
if (!typeof(T).IsEnum)
throw new ArgumentException();
var values = Enum.GetNames(typeof(T));
return values.Select(value => value.ToEnum<T>()).ToList();
}
/// <summary>
/// Present the enum values as a comma separated string.
/// </summary>
public static string GetValues<T>()
{
if (!typeof(T).IsEnum)
throw new ArgumentException();
var values = Enum.GetNames(typeof(T));
return string.Join(", ", values);
}
}
I've done something that works for me and very simple. Probably not efficient due to dynamic casting usage. But perhaps you could like it?
public static T SetFlag<T>(this Enum value, T flag, bool set)
{
Type underlyingType = Enum.GetUnderlyingType(value.GetType());
// note: AsInt mean: math integer vs enum (not the c# int type)
dynamic valueAsInt = Convert.ChangeType(value, underlyingType);
dynamic flagAsInt = Convert.ChangeType(flag, underlyingType);
if (set)
{
valueAsInt |= flagAsInt;
}
else
{
valueAsInt &= ~flagAsInt;
}
return (T)valueAsInt;
}
I'm not sure what your question is here, but if you're asking if this is possible, I'd have to say that it isn't, not with this exact syntax.
Enums are value types, and as such, are passed by value. So a method, such as SetFlag, that receives an enum value will receive a COPY of it. Even if it sets a flag, that change would be confined to the method scope, not to the enum that it's called on.
You can pass it to a method with the ref modifier, like this: SetFlag(ref enumVariable, EnumType.SingleFlag) but this isn't supported as an extension method, as far as I know.
What you can do is either create a general enum helper class:
public static class EnumHelper
{
public void SetFlag<TEnum>(ref TEnum enumValue, TEnum flag)
{
enumValue = enumValue | flag;
}
}
or, alternately, create a SetFlag method that returns a new value rather than modifying the existing variable.
public static TEnum SetFlag<TEnum>(this TEnum enumValue, TEnum flag)
{
return enumValue | flag;
}
Maybe not as pretty as you'd hoped but you can do it quite simply :)
enumVariable |= EnumType.SingleFlag;
You maybe need to implement the method for each enum because you can't constraint a enum this way:
public static T SetFlag<T>(this T #this, T flag, Boolean state) where T : enum { ... }
Anyway operator overloads are not allowed in C# on generic types, so you can't use the generic type T without casting.
Solution
So your extension methods must look like this:
public static MyFlag SetFlag(this MyFlag #this, MyFlag flag, Boolean state)
{
return state ? (#this | flag) : (#this & ~flag);
}

Validate Enum Values

I need to validate an integer to know if is a valid enum value.
What is the best way to do this in C#?
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)
IMHO the post marked as the answer is incorrect.
Parameter and data validation is one of the things that was drilled into me decades ago.
WHY
Validation is required because essentially any integer value can be assigned to an enum without throwing an error.
I spent many days researching C# enum validation because it is a necessary function in many cases.
WHERE
The main purpose in enum validation for me is in validating data read from a file: you never know if the file has been corrupted, or was modified externally, or was hacked on purpose.
And with enum validation of application data pasted from the clipboard: you never know if the user has edited the clipboard contents.
That said, I spent days researching and testing many methods including profiling the performance of every method I could find or design.
Making calls into anything in System.Enum is so slow that it was a noticeable performance penalty on functions that contained hundreds or thousands of objects that had one or more enums in their properties that had to be validated for bounds.
Bottom line, stay away from everything in the System.Enum class when validating enum values, it is dreadfully slow.
RESULT
The method that I currently use for enum validation will probably draw rolling eyes from many programmers here, but it is imho the least evil for my specific application design.
I define one or two constants that are the upper and (optionally) lower bounds of the enum, and use them in a pair of if() statements for validation.
One downside is that you must be sure to update the constants if you change the enum.
This method also only works if the enum is an "auto" style where each enum element is an incremental integer value such as 0,1,2,3,4,.... It won't work properly with Flags or enums that have values that are not incremental.
Also note that this method is almost as fast as regular if "<" ">" on regular int32s (which scored 38,000 ticks on my tests).
For example:
public const MyEnum MYENUM_MINIMUM = MyEnum.One;
public const MyEnum MYENUM_MAXIMUM = MyEnum.Four;
public enum MyEnum
{
One,
Two,
Three,
Four
};
public static MyEnum Validate(MyEnum value)
{
if (value < MYENUM_MINIMUM) { return MYENUM_MINIMUM; }
if (value > MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }
return value;
}
PERFORMANCE
For those who are interested, I profiled the following variations on an enum validation, and here are the results.
The profiling was performed on release compile in a loop of one million times on each method with a random integer input value. Each test was ran more than 10 times and averaged. The tick results include the total time to execute which will include the random number generation etc. but those will be constant across the tests. 1 tick = 10ns.
Note that the code here isn't the complete test code, it is only the basic enum validation method. There were also a lot of additional variations on these that were tested, and all of them with results similar to those shown here that benched 1,800,000 ticks.
Listed slowest to fastest with rounded results, hopefully no typos.
Bounds determined in Method = 13,600,000 ticks
public static T Clamp<T>(T value)
{
int minimum = Enum.GetValues(typeof(T)).GetLowerBound(0);
int maximum = Enum.GetValues(typeof(T)).GetUpperBound(0);
if (Convert.ToInt32(value) < minimum) { return (T)Enum.ToObject(typeof(T), minimum); }
if (Convert.ToInt32(value) > maximum) { return (T)Enum.ToObject(typeof(T), maximum); }
return value;
}
Enum.IsDefined = 1,800,000 ticks
Note: this code version doesn't clamp to Min/Max but returns Default if out of bounds.
public static T ValidateItem<T>(T eEnumItem)
{
if (Enum.IsDefined(typeof(T), eEnumItem) == true)
return eEnumItem;
else
return default(T);
}
System.Enum Convert Int32 with casts = 1,800,000 ticks
public static Enum Clamp(this Enum value, Enum minimum, Enum maximum)
{
if (Convert.ToInt32(value) < Convert.ToInt32(minimum)) { return minimum; }
if (Convert.ToInt32(value) > Convert.ToInt32(maximum)) { return maximum; }
return value;
}
if() Min/Max Constants = 43,000 ticks = the winner by 42x and 316x faster.
public static MyEnum Clamp(MyEnum value)
{
if (value < MYENUM_MINIMUM) { return MYENUM_MINIMUM; }
if (value > MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }
return value;
}
-eol-
As others have mentioned, Enum.IsDefined is slow, something you have to be aware of if it's in a loop.
When doing multiple comparisons, a speedier method is to first put the values into a HashSet. Then simply use Contains to check whether the value is valid, like so:
int userInput = 4;
// below, Enum.GetValues converts enum to array. We then convert the array to hashset.
HashSet<int> validVals = new HashSet<int>((int[])Enum.GetValues(typeof(MyEnum)));
// the following could be in a loop, or do multiple comparisons, etc.
if (validVals.Contains(userInput))
{
// is valid
}
Update 2022-09-27
As of .NET 5, a fast, generic overload is available: Enum.IsDefined<TEnum>(TEnum value).
The generic overload alleviates the performance issues of the non-generic one.
Original Answer
Here is a fast generic solution, using a statically-constucted HashSet<T>.
You can define this once in your toolbox, and then use it for all your enum validation.
public static class EnumHelpers
{
/// <summary>
/// Returns whether the given enum value is a defined value for its type.
/// Throws if the type parameter is not an enum type.
/// </summary>
public static bool IsDefined<T>(T enumValue)
{
if (typeof(T).BaseType != typeof(System.Enum)) throw new ArgumentException($"{nameof(T)} must be an enum type.");
return EnumValueCache<T>.DefinedValues.Contains(enumValue);
}
/// <summary>
/// Statically caches each defined value for each enum type for which this class is accessed.
/// Uses the fact that static things exist separately for each distinct type parameter.
/// </summary>
internal static class EnumValueCache<T>
{
public static HashSet<T> DefinedValues { get; }
static EnumValueCache()
{
if (typeof(T).BaseType != typeof(System.Enum)) throw new Exception($"{nameof(T)} must be an enum type.");
DefinedValues = new HashSet<T>((T[])System.Enum.GetValues(typeof(T)));
}
}
}
Note that this approach is easily extended to enum parsing as well, by using a dictionary with string keys (minding case-insensitivity and numeric string representations).
Brad Abrams specifically warns against Enum.IsDefined in his post The Danger of Oversimplification.
The best way to get rid of this requirement (that is, the need to validate enums) is to remove ways where users can get it wrong, e.g., an input box of some sort. Use enums with drop downs, for example, to enforce only valid enums.
This answer is in response to deegee's answer which raises the performance issues of System.Enum so should not be taken as my preferred generic answer, more addressing enum validation in tight performance scenarios.
If you have a mission critical performance issue where slow but functional code is being run in a tight loop then I personally would look at moving that code out of the loop if possible instead of solving by reducing functionality. Constraining the code to only support contiguous enums could be a nightmare to find a bug if, for example, somebody in the future decides to deprecate some enum values. Simplistically you could just call Enum.GetValues once, right at the start to avoid triggering all the reflection, etc thousands of times. That should give you an immediate performance increase. If you need more performance and you know that a lot of your enums are contiguous (but you still want to support 'gappy' enums) you could go a stage further and do something like:
public abstract class EnumValidator<TEnum> where TEnum : struct, IConvertible
{
protected static bool IsContiguous
{
get
{
int[] enumVals = Enum.GetValues(typeof(TEnum)).Cast<int>().ToArray();
int lowest = enumVals.OrderBy(i => i).First();
int highest = enumVals.OrderByDescending(i => i).First();
return !Enumerable.Range(lowest, highest).Except(enumVals).Any();
}
}
public static EnumValidator<TEnum> Create()
{
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException("Please use an enum!");
}
return IsContiguous ? (EnumValidator<TEnum>)new ContiguousEnumValidator<TEnum>() : new JumbledEnumValidator<TEnum>();
}
public abstract bool IsValid(int value);
}
public class JumbledEnumValidator<TEnum> : EnumValidator<TEnum> where TEnum : struct, IConvertible
{
private readonly int[] _values;
public JumbledEnumValidator()
{
_values = Enum.GetValues(typeof (TEnum)).Cast<int>().ToArray();
}
public override bool IsValid(int value)
{
return _values.Contains(value);
}
}
public class ContiguousEnumValidator<TEnum> : EnumValidator<TEnum> where TEnum : struct, IConvertible
{
private readonly int _highest;
private readonly int _lowest;
public ContiguousEnumValidator()
{
List<int> enumVals = Enum.GetValues(typeof (TEnum)).Cast<int>().ToList();
_lowest = enumVals.OrderBy(i => i).First();
_highest = enumVals.OrderByDescending(i => i).First();
}
public override bool IsValid(int value)
{
return value >= _lowest && value <= _highest;
}
}
Where your loop becomes something like:
//Pre import-loop
EnumValidator< MyEnum > enumValidator = EnumValidator< MyEnum >.Create();
while(import) //Tight RT loop.
{
bool isValid = enumValidator.IsValid(theValue);
}
I'm sure the EnumValidator classes could written more efficiently (it’s just a quick hack to demonstrate) but quite frankly who cares what happens outside the import loop? The only bit that needs to be super-fast is within the loop. This was the reason for taking the abstract class route, to avoid an unnecessary if-enumContiguous-then-else in the loop (the factory Create essentially does this upfront).
You will note a bit of hypocrisy, for brevity this code constrains functionality to int-enums. I should be making use of IConvertible rather than using int's directly but this answer is already wordy enough!
Building upon Timo's answer, here is an even faster, safer and simpler solution, provided as an extension method.
public static class EnumExtensions
{
/// <summary>Whether the given value is defined on its enum type.</summary>
public static bool IsDefined<T>(this T enumValue) where T : Enum
{
return EnumValueCache<T>.DefinedValues.Contains(enumValue);
}
private static class EnumValueCache<T> where T : Enum
{
public static readonly HashSet<T> DefinedValues = new HashSet<T>((T[])Enum.GetValues(typeof(T)));
}
}
Usage:
if (myEnumValue.IsDefined()) { ... }
Update - it's even now cleaner in .NET 5:
public static class EnumExtensions
{
/// <summary>Whether the given value is defined on its enum type.</summary>
public static bool IsDefined<T>(this T enumValue) where T : struct, Enum
{
return EnumValueCache<T>.DefinedValues.Contains(enumValue);
}
private static class EnumValueCache<T> where T : struct, Enum
{
public static readonly HashSet<T> DefinedValues = new(Enum.GetValues<T>());
}
}
This is how I do it based on multiple posts online. The reason for doing this is to make sure enums marked with Flags attribute can also be successfully validated.
public static TEnum ParseEnum<TEnum>(string valueString, string parameterName = null)
{
var parsed = (TEnum)Enum.Parse(typeof(TEnum), valueString, true);
decimal d;
if (!decimal.TryParse(parsed.ToString(), out d))
{
return parsed;
}
if (!string.IsNullOrEmpty(parameterName))
{
throw new ArgumentException(string.Format("Bad parameter value. Name: {0}, value: {1}", parameterName, valueString), parameterName);
}
else
{
throw new ArgumentException("Bad value. Value: " + valueString);
}
}
You can use the FluentValidation for your project. Here is a simple example for the "Enum Validation"
Let's create a EnumValidator class with using FluentValidation;
public class EnumValidator<TEnum> : AbstractValidator<TEnum> where TEnum : struct, IConvertible, IComparable, IFormattable
{
public EnumValidator(string message)
{
RuleFor(a => a).Must(a => typeof(TEnum).IsEnum).IsInEnum().WithMessage(message);
}
}
Now we created the our enumvalidator class; let's create the a class to call enumvalidor class;
public class Customer
{
public string Name { get; set; }
public Address address{ get; set; }
public AddressType type {get; set;}
}
public class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
}
public enum AddressType
{
HOME,
WORK
}
Its time to call our enum validor for the address type in customer class.
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(x => x.type).SetValidator(new EnumValidator<AddressType>("errormessage");
}
}
To expound on the performance scaling specifically regarding Timo/Matt Jenkins method:
Consider the following code:
//System.Diagnostics - Stopwatch
//System - ConsoleColor
//System.Linq - Enumerable
Stopwatch myTimer = Stopwatch.StartNew();
int myCyclesMin = 0;
int myCyclesCount = 10000000;
long myExt_IsDefinedTicks;
long myEnum_IsDefinedTicks;
foreach (int lCycles in Enumerable.Range(myCyclesMin, myCyclesMax))
{
Console.WriteLine(string.Format("Cycles: {0}", lCycles));
myTimer.Restart();
foreach (int _ in Enumerable.Range(0, lCycles)) { ConsoleColor.Green.IsDefined(); }
myExt_IsDefinedTicks = myTimer.ElapsedTicks;
myTimer.Restart();
foreach (int _ in Enumerable.Range(0, lCycles)) { Enum.IsDefined(typeof(ConsoleColor), ConsoleColor.Green); }
myEnum_IsDefinedTicks = myTimer.E
Console.WriteLine(string.Format("object.IsDefined() Extension Elapsed: {0}", myExt_IsDefinedTicks.ToString()));
Console.WriteLine(string.Format("Enum.IsDefined(Type, object): {0}", myEnum_IsDefinedTicks.ToString()));
if (myExt_IsDefinedTicks == myEnum_IsDefinedTicks) { Console.WriteLine("Same"); }
else if (myExt_IsDefinedTicks < myEnum_IsDefinedTicks) { Console.WriteLine("Extension"); }
else if (myExt_IsDefinedTicks > myEnum_IsDefinedTicks) { Console.WriteLine("Enum"); }
}
Output starts out like the following:
Cycles: 0
object.IsDefined() Extension Elapsed: 399
Enum.IsDefined(Type, object): 31
Enum
Cycles: 1
object.IsDefined() Extension Elapsed: 213654
Enum.IsDefined(Type, object): 1077
Enum
Cycles: 2
object.IsDefined() Extension Elapsed: 108
Enum.IsDefined(Type, object): 112
Extension
Cycles: 3
object.IsDefined() Extension Elapsed: 9
Enum.IsDefined(Type, object): 30
Extension
Cycles: 4
object.IsDefined() Extension Elapsed: 9
Enum.IsDefined(Type, object): 35
Extension
This seems to indicate there is a steep setup cost for the static hashset object (in my environment, approximately 15-20ms.
Reversing which method is called first doesn't change that the first call to the extension method (to set up the static hashset) is quite lengthy. Enum.IsDefined(typeof(T), object) is also longer than normal for the first cycle, but, interestingly, much less so.
Based on this, it appears Enum.IsDefined(typeof(T), object) is actually faster until lCycles = 50000 or so.
I'm unsure why Enum.IsDefined(typeof(T), object) gets faster at both 2 and 3 lookups before it starts rising. Clearly there's some process going on internally as object.IsDefined() also takes markedly longer for the first 2 lookups before settling in to be bleeding fast.
Another way to phrase this is that if you need to lots of lookups with any other remotely long activity (perhaps a file operation like an open) that will add a few milliseconds, the initial setup for object.IsDefined() will be swallowed up (especially if async) and become mostly unnoticeable. At that point, Enum.IsDefined(typeof(T), object) takes roughly 5x longer to execute.
Basically, if you don't have literally thousands of calls to make for the same Enum, I'm not sure how hashing the contents is going to save you time over your program execution. Enum.IsDefined(typeof(T), object) may have conceptual performance problems, but ultimately, it's fast enough until you need it thousands of times for the same enum.
As an interesting side note, implementing the ValueCache as a hybrid dictionary yields a startup time that reaches parity with Enum.IsDefined(typeof(T), object) within ~1500 iterations. Of course, using a HashSet passes both at ~50k.
So, my advice: If your entire program is validating the same enum (validating different enums causes the same level of startup delay, once for each different enum) less than 1500 times, use Enum.IsDefined(typeof(T), object). If you're between 1500 and 50k, use a HybridDictionary for your hashset, the initial cache populate is roughly 10x faster. Anything over 50k iterations, HashSet is a pretty clear winner.
Also keep in mind that we are talking in Ticks. In .Net a 10,000 ticks is 1 ms.
For full disclosure I also tested List as a cache, and it's about 1/3 the populate time as hashset, however, for any enum over 9 or so elements, it's way slower than any other method. If all your enums are less than 9 elements, (or smaller yet) it may be the fastest approach.
The cache defined as a HybridDictionary (yes, the keys and values are the same. Yes, it's quite a bit harder to read than the simpler answers referenced above):
//System.Collections.Specialized - HybridDictionary
private static class EnumHybridDictionaryValueCache<T> where T : Enum
{
static T[] enumValues = (T[])Enum.GetValues(typeof(T));
static HybridDictionary PopulateDefinedValues()
{
HybridDictionary myDictionary = new HybridDictionary(enumValues.Length);
foreach (T lEnumValue in enumValues)
{
//Has to be unique, values are actually based on the int value. Enums with multiple aliases for one value will fail without checking.
//Check implicitly by using assignment.
myDictionary[lEnumValue] = lEnumValue;
}
return myDictionary;
}
public static readonly HybridDictionary DefinedValues = PopulateDefinedValues();
}
I found this link that answers it quite well. It uses:
(ENUMTYPE)Enum.ToObject(typeof(ENUMTYPE), INT)
To validate if a value is a valid value in an enumeration, you only need to call the static method Enum.IsDefined.
int value = 99;//Your int value
if (Enum.IsDefined(typeof(your_enum_type), value))
{
//Todo when value is valid
}else{
//Todo when value is not valid
}

Categories