5 // Miguel de Icaza (miguel@ximian.com)
6 // Nick Drochak (ndrochak@gol.com)
7 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 // (C) Ximian, Inc. http://www.ximian.com
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Globalization;
38 using System.Runtime.CompilerServices;
39 using System.Runtime.InteropServices;
43 internal struct MonoEnumInfo
46 internal Array values;
47 internal string[] names;
48 internal Hashtable name_hash;
50 static Hashtable cache;
51 static Hashtable global_cache;
52 static object global_cache_monitor;
54 [MethodImplAttribute (MethodImplOptions.InternalCall)]
55 private static extern void get_enum_info (Type enumType, out MonoEnumInfo info);
58 // These comparers are needed because enumerations must be compared
59 // using unsigned values so that negative numbers can be looked up
62 internal static SByteComparer sbyte_comparer = new SByteComparer ();
63 internal static ShortComparer short_comparer = new ShortComparer ();
64 internal static IntComparer int_comparer = new IntComparer ();
65 internal static LongComparer long_comparer = new LongComparer ();
67 internal class SByteComparer : IComparer, System.Collections.Generic.IComparer<sbyte>
69 public int Compare (object x, object y)
74 return ((byte) ix) - ((byte) iy);
77 public int Compare (sbyte ix, sbyte iy)
79 return ((byte) ix) - ((byte) iy);
83 internal class ShortComparer : IComparer, System.Collections.Generic.IComparer<short>
85 public int Compare (object x, object y)
90 return ((ushort) ix) - ((ushort) iy);
93 public int Compare (short ix, short iy)
95 return ((ushort) ix) - ((ushort) iy);
99 internal class IntComparer : IComparer, System.Collections.Generic.IComparer<int>
101 public int Compare (object x, object y)
109 if (((uint) ix) < ((uint) iy))
114 public int Compare (int ix, int iy)
119 if (((uint) ix) < ((uint) iy))
125 internal class LongComparer : IComparer, System.Collections.Generic.IComparer<long>
127 public int Compare (object x, object y)
134 if (((ulong) ix) < ((ulong) iy))
139 public int Compare (long ix, long iy)
143 if (((ulong) ix) < ((ulong) iy))
149 static MonoEnumInfo ()
151 global_cache_monitor = new object ();
152 global_cache = new Hashtable ();
155 static Hashtable Cache {
158 cache = new Hashtable ();
163 private MonoEnumInfo (MonoEnumInfo other)
166 values = other.values;
168 name_hash = other.name_hash;
171 internal static void GetInfo (Type enumType, out MonoEnumInfo info)
173 /* First check the thread-local cache without locking */
174 if (Cache.ContainsKey (enumType)) {
175 info = (MonoEnumInfo) cache [enumType];
178 /* Threads could die, so keep a global cache too */
179 lock (global_cache_monitor) {
180 if (global_cache.ContainsKey (enumType)) {
181 object boxedInfo = global_cache [enumType];
182 cache [enumType] = boxedInfo;
183 info = (MonoEnumInfo)boxedInfo;
188 get_enum_info (enumType, out info);
191 Type et = Enum.GetUnderlyingType (enumType);
192 if (et == typeof (int))
194 else if (et == typeof (short))
196 else if (et == typeof (sbyte))
198 else if (et == typeof (long))
201 Array.Sort (info.values, info.names, ic);
202 if (info.names.Length > 50) {
203 info.name_hash = new Hashtable (info.names.Length);
204 for (int i = 0; i < info.names.Length; ++i)
205 info.name_hash [info.names [i]] = i;
207 MonoEnumInfo cached = new MonoEnumInfo (info);
208 lock (global_cache_monitor) {
209 global_cache [enumType] = cached;
216 public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable
222 // IConvertible methods Start -->
223 public TypeCode GetTypeCode ()
225 return Type.GetTypeCode (GetUnderlyingType (this.GetType ()));
228 bool IConvertible.ToBoolean (IFormatProvider provider)
230 return Convert.ToBoolean (Value, provider);
233 byte IConvertible.ToByte (IFormatProvider provider)
235 return Convert.ToByte (Value, provider);
238 char IConvertible.ToChar (IFormatProvider provider)
240 return Convert.ToChar (Value, provider);
243 DateTime IConvertible.ToDateTime (IFormatProvider provider)
245 return Convert.ToDateTime (Value, provider);
248 decimal IConvertible.ToDecimal (IFormatProvider provider)
250 return Convert.ToDecimal (Value, provider);
253 double IConvertible.ToDouble (IFormatProvider provider)
255 return Convert.ToDouble (Value, provider);
258 short IConvertible.ToInt16 (IFormatProvider provider)
260 return Convert.ToInt16 (Value, provider);
263 int IConvertible.ToInt32 (IFormatProvider provider)
265 return Convert.ToInt32 (Value, provider);
268 long IConvertible.ToInt64 (IFormatProvider provider)
270 return Convert.ToInt64 (Value, provider);
273 sbyte IConvertible.ToSByte (IFormatProvider provider)
275 return Convert.ToSByte (Value, provider);
278 float IConvertible.ToSingle (IFormatProvider provider)
280 return Convert.ToSingle (Value, provider);
283 object IConvertible.ToType (Type targetType, IFormatProvider provider)
285 if (targetType == null)
286 throw new ArgumentNullException ("targetType");
287 if (targetType == typeof (string))
288 return ToString (provider);
289 return Convert.ToType (Value, targetType, provider, false);
292 ushort IConvertible.ToUInt16 (IFormatProvider provider)
294 return Convert.ToUInt16 (Value, provider);
297 uint IConvertible.ToUInt32 (IFormatProvider provider)
299 return Convert.ToUInt32 (Value, provider);
302 ulong IConvertible.ToUInt64 (IFormatProvider provider)
304 return Convert.ToUInt64 (Value, provider);
307 // <-- End IConvertible methods
309 [MethodImplAttribute (MethodImplOptions.InternalCall)]
310 private extern object get_value ();
312 // wrap the icall into a property so we don't hav to use the icall everywhere
313 private object Value {
314 get { return get_value (); }
318 public static Array GetValues (Type enumType)
320 if (enumType == null)
321 throw new ArgumentNullException ("enumType");
323 if (!enumType.IsEnum)
324 throw new ArgumentException ("enumType is not an Enum type.", "enumType");
327 MonoEnumInfo.GetInfo (enumType, out info);
328 return (Array) info.values.Clone ();
332 public static string[] GetNames (Type enumType)
334 if (enumType == null)
335 throw new ArgumentNullException ("enumType");
337 if (!enumType.IsEnum)
338 throw new ArgumentException ("enumType is not an Enum type.");
341 MonoEnumInfo.GetInfo (enumType, out info);
342 return (string []) info.names.Clone ();
346 // The faster, non-boxing version. It must use the special MonoEnumInfo.xxx_comparers
347 // to ensure that we are perfoming bitwise compares, and not signed compares.
349 // It also tries to use the non-boxing version of the various Array.BinarySearch methods
351 static int FindPosition (Type enumType, object value, Array values)
353 switch (Type.GetTypeCode (GetUnderlyingType (enumType))) {
355 sbyte [] sbyte_array = values as sbyte [];
356 return Array.BinarySearch (sbyte_array, (sbyte) value, MonoEnumInfo.sbyte_comparer);
359 byte [] byte_array = values as byte [];
360 return Array.BinarySearch (byte_array, (byte) value);
363 short [] short_array = values as short [];
364 return Array.BinarySearch (short_array, (short)value, MonoEnumInfo.short_comparer);
366 case TypeCode.UInt16:
367 ushort [] ushort_array = values as ushort [];
368 return Array.BinarySearch (ushort_array, (ushort)value);
371 int[] int_array = values as int[];
372 return Array.BinarySearch (int_array, (int)value, MonoEnumInfo.int_comparer);
374 case TypeCode.UInt32:
375 uint[] uint_array = values as uint [];
376 return Array.BinarySearch (uint_array, (uint)value);
379 long [] long_array = values as long [];
380 return Array.BinarySearch (long_array, (long) value, MonoEnumInfo.long_comparer);
382 case TypeCode.UInt64:
383 ulong [] ulong_array = values as ulong [];
384 return Array.BinarySearch (ulong_array, (ulong) value);
387 // This should never happen
388 return Array.BinarySearch (values, value);
393 public static string GetName (Type enumType, object value)
395 if (enumType == null)
396 throw new ArgumentNullException ("enumType");
398 throw new ArgumentNullException ("value");
400 if (!enumType.IsEnum)
401 throw new ArgumentException ("enumType is not an Enum type.", "enumType");
404 value = ToObject (enumType, value);
405 MonoEnumInfo.GetInfo (enumType, out info);
407 int i = FindPosition (enumType, value, info.values);
408 return (i >= 0) ? info.names [i] : null;
412 public static bool IsDefined (Type enumType, object value)
414 if (enumType == null)
415 throw new ArgumentNullException ("enumType");
417 throw new ArgumentNullException ("value");
419 if (!enumType.IsEnum)
420 throw new ArgumentException ("enumType is not an Enum type.", "enumType");
423 MonoEnumInfo.GetInfo (enumType, out info);
425 Type vType = value.GetType ();
426 if (vType == typeof(String)) {
427 return ((IList)(info.names)).Contains (value);
428 } else if ((vType == info.utype) || (vType == enumType)) {
429 value = ToObject (enumType, value);
430 MonoEnumInfo.GetInfo (enumType, out info);
432 return FindPosition (enumType, value, info.values) >= 0;
434 throw new ArgumentException("The value parameter is not the correct type."
435 + "It must be type String or the same type as the underlying type"
440 [MethodImplAttribute (MethodImplOptions.InternalCall)]
441 private static extern Type get_underlying_type (Type enumType);
444 public static Type GetUnderlyingType (Type enumType)
446 if (enumType == null)
447 throw new ArgumentNullException ("enumType");
449 if (!enumType.IsEnum)
450 throw new ArgumentException ("enumType is not an Enum type.", "enumType");
452 return get_underlying_type (enumType);
456 public static object Parse (Type enumType, string value)
458 // Note: Parameters are checked in the other overload
459 return Parse (enumType, value, false);
462 private static int FindName (Hashtable name_hash, string [] names, string name, bool ignoreCase)
465 /* For enums with many values, use a hash table */
466 if (name_hash != null) {
467 object val = name_hash [name];
471 for (int i = 0; i < names.Length; ++i) {
472 if (name == names [i])
477 for (int i = 0; i < names.Length; ++i) {
478 if (String.Compare (name, names [i], ignoreCase, CultureInfo.InvariantCulture) == 0)
485 // Helper function for dealing with [Flags]-style enums.
486 private static ulong GetValue (object value, TypeCode typeCode)
492 return (byte) ((sbyte) value);
494 return (ushort) ((short) value);
496 return (uint) ((int) value);
498 return (ulong) ((long) value);
499 case TypeCode.UInt16:
500 return (ushort) value;
501 case TypeCode.UInt32:
503 case TypeCode.UInt64:
504 return (ulong) value;
506 throw new ArgumentException ("typeCode is not a valid type code for an Enum");
509 private static char [] split_char = { ',' };
512 public static object Parse (Type enumType, string value, bool ignoreCase)
514 if (enumType == null)
515 throw new ArgumentNullException ("enumType");
518 throw new ArgumentNullException ("value");
520 if (!enumType.IsEnum)
521 throw new ArgumentException ("enumType is not an Enum type.", "enumType");
523 value = value.Trim ();
524 if (value.Length == 0)
525 throw new ArgumentException ("An empty string is not considered a valid value.");
528 if (!Parse (enumType, value, ignoreCase, out result))
529 throw new ArgumentException (String.Format ("The requested value '{0}' was not found.", value));
534 static bool Parse<TEnum> (Type enumType, string value, bool ignoreCase, out TEnum result)
536 result = default (TEnum);
539 MonoEnumInfo.GetInfo (enumType, out info);
541 // is 'value' a named constant?
542 int loc = FindName (info.name_hash, info.names, value, ignoreCase);
544 result = (TEnum) info.values.GetValue (loc);
548 TypeCode typeCode = ((Enum) info.values.GetValue (0)).GetTypeCode ();
550 // is 'value' a list of named constants?
551 if (value.IndexOf (',') != -1) {
552 string [] names = value.Split (split_char);
554 for (int i = 0; i < names.Length; ++i) {
555 loc = FindName (info.name_hash, info.names, names [i].Trim (), ignoreCase);
559 retVal |= GetValue (info.values.GetValue (loc), typeCode);
561 result = (TEnum) ToObject (enumType, retVal);
565 // is 'value' a number?
569 if (!SByte.TryParse (value, out sb))
571 result = (TEnum) ToObject (enumType, sb);
575 if (!Byte.TryParse (value, out b))
577 result = (TEnum) ToObject (enumType, b);
581 if (!Int16.TryParse (value, out i16))
583 result = (TEnum) ToObject (enumType, i16);
585 case TypeCode.UInt16:
587 if (!UInt16.TryParse (value, out u16))
589 result = (TEnum) ToObject (enumType, u16);
593 if (!Int32.TryParse (value, out i32))
595 result = (TEnum) ToObject (enumType, i32);
597 case TypeCode.UInt32:
599 if (!UInt32.TryParse (value, out u32))
601 result = (TEnum) ToObject (enumType, u32);
605 if (!Int64.TryParse (value, out i64))
607 result = (TEnum) ToObject (enumType, i64);
609 case TypeCode.UInt64:
611 if (!UInt64.TryParse (value, out u64))
613 result = (TEnum) ToObject (enumType, u64);
622 #if BOOTSTRAP_NET_4_0 || NET_4_0 || MOONLIGHT
623 public static bool TryParse<TEnum> (string value, out TEnum result) where TEnum : struct
625 return TryParse (value, false, out result);
628 public static bool TryParse<TEnum> (string value, bool ignoreCase, out TEnum result) where TEnum : struct
630 Type tenum_type = typeof (TEnum);
631 if (!tenum_type.IsEnum)
632 throw new ArgumentException("TEnum is not an Enum type.", "enumType");
634 result = default (TEnum);
636 if (value == null || value.Trim ().Length == 0)
639 return Parse (tenum_type, value, ignoreCase, out result);
643 [MethodImplAttribute (MethodImplOptions.InternalCall)]
644 private extern int compare_value_to (object other);
647 /// Compares the enum value with another enum value of the same type.
651 public int CompareTo (object target)
658 thisType = this.GetType ();
659 if (target.GetType() != thisType) {
660 throw new ArgumentException (String.Format (
661 "Object must be the same type as the enum. The type passed in was {0}; the enum type was {1}.",
662 target.GetType(), thisType));
665 return compare_value_to (target);
668 public override string ToString ()
670 return ToString ("G");
673 [Obsolete("Provider is ignored, just use ToString")]
674 public string ToString (IFormatProvider provider)
676 return ToString ("G", provider);
679 public string ToString (String format)
681 if (format == String.Empty || format == null)
684 return Format (this.GetType (), this.Value, format);
687 [Obsolete("Provider is ignored, just use ToString")]
688 public string ToString (String format, IFormatProvider provider)
690 // provider is not used for Enums
692 if (format == String.Empty || format == null) {
695 return Format (this.GetType(), this.Value, format);
699 public static object ToObject (Type enumType, byte value)
701 return ToObject (enumType, (object)value);
705 public static object ToObject (Type enumType, short value)
707 return ToObject (enumType, (object)value);
711 public static object ToObject (Type enumType, int value)
713 return ToObject (enumType, (object)value);
717 public static object ToObject (Type enumType, long value)
719 return ToObject (enumType, (object)value);
723 [MethodImplAttribute(MethodImplOptions.InternalCall)]
724 public static extern object ToObject (Type enumType, object value);
727 [CLSCompliant (false)]
728 public static object ToObject (Type enumType, sbyte value)
730 return ToObject (enumType, (object)value);
734 [CLSCompliant (false)]
735 public static object ToObject (Type enumType, ushort value)
737 return ToObject (enumType, (object)value);
741 [CLSCompliant (false)]
742 public static object ToObject (Type enumType, uint value)
744 return ToObject (enumType, (object)value);
748 [CLSCompliant (false)]
749 public static object ToObject (Type enumType, ulong value)
751 return ToObject (enumType, (object)value);
754 public override bool Equals (object obj)
756 return DefaultEquals (this, obj);
759 [MethodImplAttribute (MethodImplOptions.InternalCall)]
760 private extern int get_hashcode ();
762 public override int GetHashCode ()
764 return get_hashcode ();
767 private static string FormatSpecifier_X (Type enumType, object value, bool upper)
769 switch (Type.GetTypeCode (enumType)) {
771 return ((sbyte)value).ToString (upper ? "X2" : "x2");
773 return ((byte)value).ToString (upper ? "X2" : "x2");
775 return ((short)value).ToString (upper ? "X4" : "x4");
776 case TypeCode.UInt16:
777 return ((ushort)value).ToString (upper ? "X4" : "x4");
779 return ((int)value).ToString (upper ? "X8" : "x8");
780 case TypeCode.UInt32:
781 return ((uint)value).ToString (upper ? "X8" : "x8");
783 return ((long)value).ToString (upper ? "X16" : "x16");
784 case TypeCode.UInt64:
785 return ((ulong)value).ToString (upper ? "X16" : "x16");
787 throw new Exception ("Invalid type code for enumeration.");
791 static string FormatFlags (Type enumType, object value)
793 string retVal = String.Empty;
795 MonoEnumInfo.GetInfo (enumType, out info);
796 string asString = value.ToString ();
797 if (asString == "0") {
798 retVal = GetName (enumType, value);
803 // This is ugly, yes. We need to handle the different integer
804 // types for enums. If someone else has a better idea, be my guest.
805 switch (((Enum)info.values.GetValue (0)).GetTypeCode ()) {
806 case TypeCode.SByte: {
807 sbyte flags = (sbyte) value;
809 for (int i = info.values.Length - 1; i >= 0; i--) {
810 enumValue = (sbyte) info.values.GetValue (i);
814 if ((flags & enumValue) == enumValue) {
815 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
819 if (flags != 0) return asString;
822 case TypeCode.Byte: {
823 byte flags = (byte) value;
825 for (int i = info.values.Length - 1; i >= 0; i--) {
826 enumValue = (byte) info.values.GetValue (i);
830 if ((flags & enumValue) == enumValue) {
831 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
835 if (flags != 0) return asString;
838 case TypeCode.Int16: {
839 short flags = (short) value;
841 for (int i = info.values.Length - 1; i >= 0; i--) {
842 enumValue = (short) info.values.GetValue (i);
846 if ((flags & enumValue) == enumValue) {
847 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
851 if (flags != 0) return asString;
854 case TypeCode.Int32: {
855 int flags = (int) value;
857 for (int i = info.values.Length - 1; i >= 0; i--) {
858 enumValue = (int) info.values.GetValue (i);
862 if ((flags & enumValue) == enumValue) {
863 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
867 if (flags != 0) return asString;
870 case TypeCode.UInt16: {
871 ushort flags = (ushort) value;
873 for (int i = info.values.Length - 1; i >= 0; i--) {
874 enumValue = (ushort) info.values.GetValue (i);
878 if ((flags & enumValue) == enumValue) {
879 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
883 if (flags != 0) return asString;
886 case TypeCode.UInt32: {
887 uint flags = (uint) value;
889 for (int i = info.values.Length - 1; i >= 0; i--) {
890 enumValue = (uint) info.values.GetValue (i);
894 if ((flags & enumValue) == enumValue) {
895 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
899 if (flags != 0) return asString;
902 case TypeCode.Int64: {
903 long flags = (long) value;
905 for (int i = info.values.Length - 1; i >= 0; i--) {
906 enumValue = (long) info.values.GetValue (i);
910 if ((flags & enumValue) == enumValue) {
911 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
915 if (flags != 0) return asString;
918 case TypeCode.UInt64: {
919 ulong flags = (ulong) value;
921 for (int i = info.values.Length - 1; i >= 0; i--) {
922 enumValue = (ulong) info.values.GetValue (i);
926 if ((flags & enumValue) == enumValue) {
927 retVal = info.names[i] + (retVal == String.Empty ? String.Empty : ", ") + retVal;
931 if (flags != 0) return asString;
936 if (retVal == String.Empty)
943 public static string Format (Type enumType, object value, string format)
945 if (enumType == null)
946 throw new ArgumentNullException ("enumType");
948 throw new ArgumentNullException ("value");
950 throw new ArgumentNullException ("format");
952 if (!enumType.IsEnum)
953 throw new ArgumentException ("enumType is not an Enum type.", "enumType");
955 Type vType = value.GetType();
956 Type underlyingType = Enum.GetUnderlyingType (enumType);
958 if (vType != enumType)
959 throw new ArgumentException (string.Format(CultureInfo.InvariantCulture,
960 "Object must be the same type as the enum. The type" +
961 " passed in was {0}; the enum type was {1}.",
962 vType.FullName, enumType.FullName));
963 } else if (vType != underlyingType) {
964 throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
965 "Enum underlying type and the object must be the same type" +
966 " or object. Type passed in was {0}; the enum underlying" +
967 " type was {1}.", vType.FullName, underlyingType.FullName));
970 if (format.Length != 1)
971 throw new FormatException ("Format String can be only \"G\",\"g\",\"X\"," +
972 "\"x\",\"F\",\"f\",\"D\" or \"d\".");
974 char formatChar = format [0];
976 if ((formatChar == 'G' || formatChar == 'g')) {
977 if (!enumType.IsDefined (typeof(FlagsAttribute), false)) {
978 retVal = GetName (enumType, value);
980 retVal = value.ToString();
988 if ((formatChar == 'f' || formatChar == 'F'))
989 return FormatFlags (enumType, value);
991 retVal = String.Empty;
992 switch (formatChar) {
994 retVal = FormatSpecifier_X (enumType, value, true);
997 retVal = FormatSpecifier_X (enumType, value, false);
1001 if (underlyingType == typeof (ulong)) {
1002 ulong ulongValue = Convert.ToUInt64 (value);
1003 retVal = ulongValue.ToString ();
1005 long longValue = Convert.ToInt64 (value);
1006 retVal = longValue.ToString ();
1010 throw new FormatException ("Format String can be only \"G\",\"g\",\"X\"," +
1011 "\"x\",\"F\",\"f\",\"D\" or \"d\".");
1015 #if NET_4_0 || MOONLIGHT
1016 public bool HasFlag (Enum flag)
1018 ulong mvalue = Convert.ToUInt64 (get_value (), null);
1019 ulong fvalue = Convert.ToUInt64 (flag, null);
1021 return ((mvalue & fvalue) == fvalue);