Enum.cs 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Globalization;
  7. using System.Reflection;
  8. using System.Runtime.CompilerServices;
  9. using Internal.Runtime.CompilerServices;
  10. #if CORERT
  11. using CorElementType = System.Runtime.RuntimeImports.RhCorElementType;
  12. using RuntimeType = System.Type;
  13. using EnumInfo = Internal.Runtime.Augments.EnumInfo;
  14. #endif
  15. // The code below includes partial support for float/double and
  16. // pointer sized enums.
  17. //
  18. // The type loader does not prohibit such enums, and older versions of
  19. // the ECMA spec include them as possible enum types.
  20. //
  21. // However there are many things broken throughout the stack for
  22. // float/double/intptr/uintptr enums. There was a conscious decision
  23. // made to not fix the whole stack to work well for them because of
  24. // the right behavior is often unclear, and it is hard to test and
  25. // very low value because of such enums cannot be expressed in C#.
  26. namespace System
  27. {
  28. [Serializable]
  29. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  30. public abstract partial class Enum : ValueType, IComparable, IFormattable, IConvertible
  31. {
  32. #region Private Constants
  33. private const char EnumSeparatorChar = ',';
  34. #endregion
  35. #region Private Static Methods
  36. private string ValueToString()
  37. {
  38. ref byte data = ref this.GetRawData();
  39. return (InternalGetCorElementType()) switch
  40. {
  41. CorElementType.ELEMENT_TYPE_I1 => Unsafe.As<byte, sbyte>(ref data).ToString(),
  42. CorElementType.ELEMENT_TYPE_U1 => data.ToString(),
  43. CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As<byte, bool>(ref data).ToString(),
  44. CorElementType.ELEMENT_TYPE_I2 => Unsafe.As<byte, short>(ref data).ToString(),
  45. CorElementType.ELEMENT_TYPE_U2 => Unsafe.As<byte, ushort>(ref data).ToString(),
  46. CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As<byte, char>(ref data).ToString(),
  47. CorElementType.ELEMENT_TYPE_I4 => Unsafe.As<byte, int>(ref data).ToString(),
  48. CorElementType.ELEMENT_TYPE_U4 => Unsafe.As<byte, uint>(ref data).ToString(),
  49. CorElementType.ELEMENT_TYPE_R4 => Unsafe.As<byte, float>(ref data).ToString(),
  50. CorElementType.ELEMENT_TYPE_I8 => Unsafe.As<byte, long>(ref data).ToString(),
  51. CorElementType.ELEMENT_TYPE_U8 => Unsafe.As<byte, ulong>(ref data).ToString(),
  52. CorElementType.ELEMENT_TYPE_R8 => Unsafe.As<byte, double>(ref data).ToString(),
  53. CorElementType.ELEMENT_TYPE_I => Unsafe.As<byte, IntPtr>(ref data).ToString(),
  54. CorElementType.ELEMENT_TYPE_U => Unsafe.As<byte, UIntPtr>(ref data).ToString(),
  55. _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
  56. };
  57. }
  58. private string ValueToHexString()
  59. {
  60. ref byte data = ref this.GetRawData();
  61. switch (InternalGetCorElementType())
  62. {
  63. case CorElementType.ELEMENT_TYPE_I1:
  64. case CorElementType.ELEMENT_TYPE_U1:
  65. return data.ToString("X2", null);
  66. case CorElementType.ELEMENT_TYPE_BOOLEAN:
  67. return Convert.ToByte(Unsafe.As<byte, bool>(ref data)).ToString("X2", null);
  68. case CorElementType.ELEMENT_TYPE_I2:
  69. case CorElementType.ELEMENT_TYPE_U2:
  70. case CorElementType.ELEMENT_TYPE_CHAR:
  71. return Unsafe.As<byte, ushort>(ref data).ToString("X4", null);
  72. case CorElementType.ELEMENT_TYPE_I4:
  73. case CorElementType.ELEMENT_TYPE_U4:
  74. return Unsafe.As<byte, uint>(ref data).ToString("X8", null);
  75. case CorElementType.ELEMENT_TYPE_I8:
  76. case CorElementType.ELEMENT_TYPE_U8:
  77. return Unsafe.As<byte, ulong>(ref data).ToString("X16", null);
  78. default:
  79. throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
  80. }
  81. }
  82. private static string ValueToHexString(object value)
  83. {
  84. return (Convert.GetTypeCode(value)) switch
  85. {
  86. TypeCode.SByte => ((byte)(sbyte)value).ToString("X2", null),
  87. TypeCode.Byte => ((byte)value).ToString("X2", null),
  88. TypeCode.Boolean => Convert.ToByte((bool)value).ToString("X2", null), // direct cast from bool to byte is not allowed
  89. TypeCode.Int16 => ((ushort)(short)value).ToString("X4", null),
  90. TypeCode.UInt16 => ((ushort)value).ToString("X4", null),
  91. TypeCode.Char => ((ushort)(char)value).ToString("X4", null),
  92. TypeCode.UInt32 => ((uint)value).ToString("X8", null),
  93. TypeCode.Int32 => ((uint)(int)value).ToString("X8", null),
  94. TypeCode.UInt64 => ((ulong)value).ToString("X16", null),
  95. TypeCode.Int64 => ((ulong)(long)value).ToString("X16", null),
  96. _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
  97. };
  98. }
  99. internal static string? GetEnumName(RuntimeType enumType, ulong ulValue)
  100. {
  101. return GetEnumName(GetEnumInfo(enumType), ulValue);
  102. }
  103. private static string? GetEnumName(EnumInfo enumInfo, ulong ulValue)
  104. {
  105. int index = Array.BinarySearch(enumInfo.Values, ulValue);
  106. if (index >= 0)
  107. {
  108. return enumInfo.Names[index];
  109. }
  110. return null; // return null so the caller knows to .ToString() the input
  111. }
  112. private static string? InternalFormat(RuntimeType enumType, ulong value)
  113. {
  114. EnumInfo enumInfo = GetEnumInfo(enumType);
  115. if (!enumInfo.HasFlagsAttribute)
  116. {
  117. return GetEnumName(enumInfo, value);
  118. }
  119. else // These are flags OR'ed together (We treat everything as unsigned types)
  120. {
  121. return InternalFlagsFormat(enumType, enumInfo, value);
  122. }
  123. }
  124. private static string? InternalFlagsFormat(RuntimeType enumType, ulong result)
  125. {
  126. return InternalFlagsFormat(enumType, GetEnumInfo(enumType), result);
  127. }
  128. private static string? InternalFlagsFormat(RuntimeType enumType, EnumInfo enumInfo, ulong resultValue)
  129. {
  130. Debug.Assert(enumType != null);
  131. string[] names = enumInfo.Names;
  132. ulong[] values = enumInfo.Values;
  133. Debug.Assert(names.Length == values.Length);
  134. // Values are sorted, so if the incoming value is 0, we can check to see whether
  135. // the first entry matches it, in which case we can return its name; otherwise,
  136. // we can just return "0".
  137. if (resultValue == 0)
  138. {
  139. return values.Length > 0 && values[0] == 0 ?
  140. names[0] :
  141. "0";
  142. }
  143. // With a ulong result value, regardless of the enum's base type, the maximum
  144. // possible number of consistent name/values we could have is 64, since every
  145. // value is made up of one or more bits, and when we see values and incorporate
  146. // their names, we effectively switch off those bits.
  147. Span<int> foundItems = stackalloc int[64];
  148. // Walk from largest to smallest. It's common to have a flags enum with a single
  149. // value that matches a single entry, in which case we can just return the existing
  150. // name string.
  151. int index = values.Length - 1;
  152. while (index >= 0)
  153. {
  154. if (values[index] == resultValue)
  155. {
  156. return names[index];
  157. }
  158. if (values[index] < resultValue)
  159. {
  160. break;
  161. }
  162. index--;
  163. }
  164. // Now look for multiple matches, storing the indices of the values
  165. // into our span.
  166. int resultLength = 0, foundItemsCount = 0;
  167. while (index >= 0)
  168. {
  169. ulong currentValue = values[index];
  170. if (index == 0 && currentValue == 0)
  171. {
  172. break;
  173. }
  174. if ((resultValue & currentValue) == currentValue)
  175. {
  176. resultValue -= currentValue;
  177. foundItems[foundItemsCount++] = index;
  178. resultLength = checked(resultLength + names[index].Length);
  179. }
  180. index--;
  181. }
  182. // If we exhausted looking through all the values and we still have
  183. // a non-zero result, we couldn't match the result to only named values.
  184. // In that case, we return null and let the call site just generate
  185. // a string for the integral value.
  186. if (resultValue != 0)
  187. {
  188. return null;
  189. }
  190. // We know what strings to concatenate. Do so.
  191. Debug.Assert(foundItemsCount > 0);
  192. const int SeparatorStringLength = 2; // ", "
  193. string result = string.FastAllocateString(checked(resultLength + (SeparatorStringLength * (foundItemsCount - 1))));
  194. Span<char> resultSpan = new Span<char>(ref result.GetRawStringData(), result.Length);
  195. string name = names[foundItems[--foundItemsCount]];
  196. name.AsSpan().CopyTo(resultSpan);
  197. resultSpan = resultSpan.Slice(name.Length);
  198. while (--foundItemsCount >= 0)
  199. {
  200. resultSpan[0] = EnumSeparatorChar;
  201. resultSpan[1] = ' ';
  202. resultSpan = resultSpan.Slice(2);
  203. name = names[foundItems[foundItemsCount]];
  204. name.AsSpan().CopyTo(resultSpan);
  205. resultSpan = resultSpan.Slice(name.Length);
  206. }
  207. Debug.Assert(resultSpan.IsEmpty);
  208. return result;
  209. }
  210. internal static ulong ToUInt64(object value)
  211. {
  212. // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception.
  213. // This is need since the Convert functions do overflow checks.
  214. TypeCode typeCode = Convert.GetTypeCode(value);
  215. ulong result = typeCode switch
  216. {
  217. TypeCode.SByte => (ulong)(sbyte)value,
  218. TypeCode.Byte => (byte)value,
  219. TypeCode.Boolean => Convert.ToByte((bool)value), // direct cast from bool to byte is not allowed
  220. TypeCode.Int16 => (ulong)(short)value,
  221. TypeCode.UInt16 => (ushort)value,
  222. TypeCode.Char => (ushort)(char)value,
  223. TypeCode.UInt32 => (uint)value,
  224. TypeCode.Int32 => (ulong)(int)value,
  225. TypeCode.UInt64 => (ulong)value,
  226. TypeCode.Int64 => (ulong)(long)value,
  227. _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
  228. };
  229. return result;
  230. }
  231. #endregion
  232. #region Public Static Methods
  233. public static object Parse(Type enumType, string value) =>
  234. Parse(enumType, value, ignoreCase: false);
  235. public static object Parse(Type enumType, string value, bool ignoreCase)
  236. {
  237. bool success = TryParse(enumType, value, ignoreCase, throwOnFailure: true, out object? result);
  238. Debug.Assert(success);
  239. return result!;
  240. }
  241. public static TEnum Parse<TEnum>(string value) where TEnum : struct =>
  242. Parse<TEnum>(value, ignoreCase: false);
  243. public static TEnum Parse<TEnum>(string value, bool ignoreCase) where TEnum : struct
  244. {
  245. bool success = TryParse<TEnum>(value, ignoreCase, throwOnFailure: true, out TEnum result);
  246. Debug.Assert(success);
  247. return result;
  248. }
  249. public static bool TryParse(Type enumType, string? value, out object? result) =>
  250. TryParse(enumType, value, ignoreCase: false, out result);
  251. public static bool TryParse(Type enumType, string? value, bool ignoreCase, out object? result) =>
  252. TryParse(enumType, value, ignoreCase, throwOnFailure: false, out result);
  253. private static bool TryParse(Type enumType, string? value, bool ignoreCase, bool throwOnFailure, out object? result)
  254. {
  255. // Validation on the enum type itself. Failures here are considered non-parsing failures
  256. // and thus always throw rather than returning false.
  257. RuntimeType rt = ValidateRuntimeType(enumType);
  258. ReadOnlySpan<char> valueSpan = value.AsSpan().TrimStart();
  259. if (valueSpan.Length == 0)
  260. {
  261. if (throwOnFailure)
  262. {
  263. throw value == null ?
  264. new ArgumentNullException(nameof(value)) :
  265. new ArgumentException(SR.Arg_MustContainEnumInfo, nameof(value));
  266. }
  267. result = null;
  268. return false;
  269. }
  270. int intResult;
  271. uint uintResult;
  272. bool parsed;
  273. switch (Type.GetTypeCode(rt))
  274. {
  275. case TypeCode.SByte:
  276. parsed = TryParseInt32Enum(rt, value, valueSpan, sbyte.MinValue, sbyte.MaxValue, ignoreCase, throwOnFailure, TypeCode.SByte, out intResult);
  277. result = parsed ? InternalBoxEnum(rt, intResult) : null;
  278. return parsed;
  279. case TypeCode.Int16:
  280. parsed = TryParseInt32Enum(rt, value, valueSpan, short.MinValue, short.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int16, out intResult);
  281. result = parsed ? InternalBoxEnum(rt, intResult) : null;
  282. return parsed;
  283. case TypeCode.Int32:
  284. parsed = TryParseInt32Enum(rt, value, valueSpan, int.MinValue, int.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int32, out intResult);
  285. result = parsed ? InternalBoxEnum(rt, intResult) : null;
  286. return parsed;
  287. case TypeCode.Byte:
  288. parsed = TryParseUInt32Enum(rt, value, valueSpan, byte.MaxValue, ignoreCase, throwOnFailure, TypeCode.Byte, out uintResult);
  289. result = parsed ? InternalBoxEnum(rt, uintResult) : null;
  290. return parsed;
  291. case TypeCode.UInt16:
  292. parsed = TryParseUInt32Enum(rt, value, valueSpan, ushort.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt16, out uintResult);
  293. result = parsed ? InternalBoxEnum(rt, uintResult) : null;
  294. return parsed;
  295. case TypeCode.UInt32:
  296. parsed = TryParseUInt32Enum(rt, value, valueSpan, uint.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt32, out uintResult);
  297. result = parsed ? InternalBoxEnum(rt, uintResult) : null;
  298. return parsed;
  299. case TypeCode.Int64:
  300. parsed = TryParseInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out long longResult);
  301. result = parsed ? InternalBoxEnum(rt, longResult) : null;
  302. return parsed;
  303. case TypeCode.UInt64:
  304. parsed = TryParseUInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out ulong ulongResult);
  305. result = parsed ? InternalBoxEnum(rt, (long)ulongResult) : null;
  306. return parsed;
  307. default:
  308. return TryParseRareEnum(rt, value, valueSpan, ignoreCase, throwOnFailure, out result);
  309. }
  310. }
  311. public static bool TryParse<TEnum>(string? value, out TEnum result) where TEnum : struct =>
  312. TryParse<TEnum>(value, ignoreCase: false, out result);
  313. public static bool TryParse<TEnum>(string? value, bool ignoreCase, out TEnum result) where TEnum : struct =>
  314. TryParse<TEnum>(value, ignoreCase, throwOnFailure: false, out result);
  315. private static bool TryParse<TEnum>(string? value, bool ignoreCase, bool throwOnFailure, out TEnum result) where TEnum : struct
  316. {
  317. // Validation on the enum type itself. Failures here are considered non-parsing failures
  318. // and thus always throw rather than returning false.
  319. if (!typeof(TEnum).IsEnum)
  320. {
  321. throw new ArgumentException(SR.Arg_MustBeEnum, nameof(TEnum));
  322. }
  323. ReadOnlySpan<char> valueSpan = value.AsSpan().TrimStart();
  324. if (valueSpan.Length == 0)
  325. {
  326. if (throwOnFailure)
  327. {
  328. throw value == null ?
  329. new ArgumentNullException(nameof(value)) :
  330. new ArgumentException(SR.Arg_MustContainEnumInfo, nameof(value));
  331. }
  332. result = default;
  333. return false;
  334. }
  335. int intResult;
  336. uint uintResult;
  337. bool parsed;
  338. RuntimeType rt = (RuntimeType)typeof(TEnum);
  339. switch (Type.GetTypeCode(typeof(TEnum)))
  340. {
  341. case TypeCode.SByte:
  342. parsed = TryParseInt32Enum(rt, value, valueSpan, sbyte.MinValue, sbyte.MaxValue, ignoreCase, throwOnFailure, TypeCode.SByte, out intResult);
  343. sbyte sbyteResult = (sbyte)intResult;
  344. result = Unsafe.As<sbyte, TEnum>(ref sbyteResult);
  345. return parsed;
  346. case TypeCode.Int16:
  347. parsed = TryParseInt32Enum(rt, value, valueSpan, short.MinValue, short.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int16, out intResult);
  348. short shortResult = (short)intResult;
  349. result = Unsafe.As<short, TEnum>(ref shortResult);
  350. return parsed;
  351. case TypeCode.Int32:
  352. parsed = TryParseInt32Enum(rt, value, valueSpan, int.MinValue, int.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int32, out intResult);
  353. result = Unsafe.As<int, TEnum>(ref intResult);
  354. return parsed;
  355. case TypeCode.Byte:
  356. parsed = TryParseUInt32Enum(rt, value, valueSpan, byte.MaxValue, ignoreCase, throwOnFailure, TypeCode.Byte, out uintResult);
  357. byte byteResult = (byte)uintResult;
  358. result = Unsafe.As<byte, TEnum>(ref byteResult);
  359. return parsed;
  360. case TypeCode.UInt16:
  361. parsed = TryParseUInt32Enum(rt, value, valueSpan, ushort.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt16, out uintResult);
  362. ushort ushortResult = (ushort)uintResult;
  363. result = Unsafe.As<ushort, TEnum>(ref ushortResult);
  364. return parsed;
  365. case TypeCode.UInt32:
  366. parsed = TryParseUInt32Enum(rt, value, valueSpan, uint.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt32, out uintResult);
  367. result = Unsafe.As<uint, TEnum>(ref uintResult);
  368. return parsed;
  369. case TypeCode.Int64:
  370. parsed = TryParseInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out long longResult);
  371. result = Unsafe.As<long, TEnum>(ref longResult);
  372. return parsed;
  373. case TypeCode.UInt64:
  374. parsed = TryParseUInt64Enum(rt, value, valueSpan, ignoreCase, throwOnFailure, out ulong ulongResult);
  375. result = Unsafe.As<ulong, TEnum>(ref ulongResult);
  376. return parsed;
  377. default:
  378. parsed = TryParseRareEnum(rt, value, valueSpan, ignoreCase, throwOnFailure, out object? objectResult);
  379. result = parsed ? (TEnum)objectResult! : default;
  380. return parsed;
  381. }
  382. }
  383. /// <summary>Tries to parse the value of an enum with known underlying types that fit in an Int32 (Int32, Int16, and SByte).</summary>
  384. private static bool TryParseInt32Enum(
  385. RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, int minInclusive, int maxInclusive, bool ignoreCase, bool throwOnFailure, TypeCode type, out int result)
  386. {
  387. Debug.Assert(
  388. enumType.GetEnumUnderlyingType() == typeof(sbyte) ||
  389. enumType.GetEnumUnderlyingType() == typeof(short) ||
  390. enumType.GetEnumUnderlyingType() == typeof(int));
  391. Number.ParsingStatus status = default;
  392. if (StartsNumber(value[0]))
  393. {
  394. status = Number.TryParseInt32IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
  395. if (status == Number.ParsingStatus.OK)
  396. {
  397. if ((uint)(result - minInclusive) <= (uint)(maxInclusive - minInclusive))
  398. {
  399. return true;
  400. }
  401. status = Number.ParsingStatus.Overflow;
  402. }
  403. }
  404. if (status == Number.ParsingStatus.Overflow)
  405. {
  406. if (throwOnFailure)
  407. {
  408. Number.ThrowOverflowException(type);
  409. }
  410. }
  411. else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
  412. {
  413. result = (int)ulongResult;
  414. Debug.Assert(result >= minInclusive && result <= maxInclusive);
  415. return true;
  416. }
  417. result = 0;
  418. return false;
  419. }
  420. /// <summary>Tries to parse the value of an enum with known underlying types that fit in a UInt32 (UInt32, UInt16, and Byte).</summary>
  421. private static bool TryParseUInt32Enum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, uint maxInclusive, bool ignoreCase, bool throwOnFailure, TypeCode type, out uint result)
  422. {
  423. Debug.Assert(
  424. enumType.GetEnumUnderlyingType() == typeof(byte) ||
  425. enumType.GetEnumUnderlyingType() == typeof(ushort) ||
  426. enumType.GetEnumUnderlyingType() == typeof(uint));
  427. Number.ParsingStatus status = default;
  428. if (StartsNumber(value[0]))
  429. {
  430. status = Number.TryParseUInt32IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
  431. if (status == Number.ParsingStatus.OK)
  432. {
  433. if (result <= maxInclusive)
  434. {
  435. return true;
  436. }
  437. status = Number.ParsingStatus.Overflow;
  438. }
  439. }
  440. if (status == Number.ParsingStatus.Overflow)
  441. {
  442. if (throwOnFailure)
  443. {
  444. Number.ThrowOverflowException(type);
  445. }
  446. }
  447. else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
  448. {
  449. result = (uint)ulongResult;
  450. Debug.Assert(result <= maxInclusive);
  451. return true;
  452. }
  453. result = 0;
  454. return false;
  455. }
  456. /// <summary>Tries to parse the value of an enum with Int64 as the underlying type.</summary>
  457. private static bool TryParseInt64Enum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out long result)
  458. {
  459. Debug.Assert(enumType.GetEnumUnderlyingType() == typeof(long));
  460. Number.ParsingStatus status = default;
  461. if (StartsNumber(value[0]))
  462. {
  463. status = Number.TryParseInt64IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
  464. if (status == Number.ParsingStatus.OK)
  465. {
  466. return true;
  467. }
  468. }
  469. if (status == Number.ParsingStatus.Overflow)
  470. {
  471. if (throwOnFailure)
  472. {
  473. Number.ThrowOverflowException(TypeCode.Int64);
  474. }
  475. }
  476. else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
  477. {
  478. result = (long)ulongResult;
  479. return true;
  480. }
  481. result = 0;
  482. return false;
  483. }
  484. /// <summary>Tries to parse the value of an enum with UInt64 as the underlying type.</summary>
  485. private static bool TryParseUInt64Enum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out ulong result)
  486. {
  487. Debug.Assert(enumType.GetEnumUnderlyingType() == typeof(ulong));
  488. Number.ParsingStatus status = default;
  489. if (StartsNumber(value[0]))
  490. {
  491. status = Number.TryParseUInt64IntegerStyle(value, NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture.NumberFormat, out result);
  492. if (status == Number.ParsingStatus.OK)
  493. {
  494. return true;
  495. }
  496. }
  497. if (status == Number.ParsingStatus.Overflow)
  498. {
  499. if (throwOnFailure)
  500. {
  501. Number.ThrowOverflowException(TypeCode.UInt64);
  502. }
  503. }
  504. else if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out result))
  505. {
  506. return true;
  507. }
  508. result = 0;
  509. return false;
  510. }
  511. /// <summary>Tries to parse the value of an enum with an underlying type that can't be expressed in C# (e.g. char, bool, double, etc.)</summary>
  512. private static bool TryParseRareEnum(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, [NotNullWhen(true)] out object? result)
  513. {
  514. Debug.Assert(
  515. enumType.GetEnumUnderlyingType() != typeof(sbyte) &&
  516. enumType.GetEnumUnderlyingType() != typeof(byte) &&
  517. enumType.GetEnumUnderlyingType() != typeof(short) &&
  518. enumType.GetEnumUnderlyingType() != typeof(ushort) &&
  519. enumType.GetEnumUnderlyingType() != typeof(int) &&
  520. enumType.GetEnumUnderlyingType() != typeof(uint) &&
  521. enumType.GetEnumUnderlyingType() != typeof(long) &&
  522. enumType.GetEnumUnderlyingType() != typeof(ulong),
  523. "Should only be used when parsing enums with rare underlying types, those that can't be expressed in C#.");
  524. if (StartsNumber(value[0]))
  525. {
  526. Type underlyingType = GetUnderlyingType(enumType);
  527. try
  528. {
  529. result = ToObject(enumType, Convert.ChangeType(value.ToString(), underlyingType, CultureInfo.InvariantCulture)!);
  530. return true;
  531. }
  532. catch (FormatException)
  533. {
  534. // We need to Parse this as a String instead. There are cases
  535. // when you tlbimp enums that can have values of the form "3D".
  536. }
  537. catch when (!throwOnFailure)
  538. {
  539. result = null;
  540. return false;
  541. }
  542. }
  543. if (TryParseByName(enumType, originalValueString, value, ignoreCase, throwOnFailure, out ulong ulongResult))
  544. {
  545. try
  546. {
  547. result = ToObject(enumType, ulongResult);
  548. return true;
  549. }
  550. catch when (!throwOnFailure) { }
  551. }
  552. result = null;
  553. return false;
  554. }
  555. private static bool TryParseByName(RuntimeType enumType, string? originalValueString, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out ulong result)
  556. {
  557. // Find the field. Let's assume that these are always static classes because the class is an enum.
  558. EnumInfo enumInfo = GetEnumInfo(enumType);
  559. string[] enumNames = enumInfo.Names;
  560. ulong[] enumValues = enumInfo.Values;
  561. bool parsed = true;
  562. ulong localResult = 0;
  563. while (value.Length > 0)
  564. {
  565. // Find the next separator.
  566. ReadOnlySpan<char> subvalue;
  567. int endIndex = value.IndexOf(EnumSeparatorChar);
  568. if (endIndex == -1)
  569. {
  570. // No next separator; use the remainder as the next value.
  571. subvalue = value.Trim();
  572. value = default;
  573. }
  574. else if (endIndex != value.Length - 1)
  575. {
  576. // Found a separator before the last char.
  577. subvalue = value.Slice(0, endIndex).Trim();
  578. value = value.Slice(endIndex + 1);
  579. }
  580. else
  581. {
  582. // Last char was a separator, which is invalid.
  583. parsed = false;
  584. break;
  585. }
  586. // Try to match this substring against each enum name
  587. bool success = false;
  588. if (ignoreCase)
  589. {
  590. for (int i = 0; i < enumNames.Length; i++)
  591. {
  592. if (subvalue.EqualsOrdinalIgnoreCase(enumNames[i]))
  593. {
  594. localResult |= enumValues[i];
  595. success = true;
  596. break;
  597. }
  598. }
  599. }
  600. else
  601. {
  602. for (int i = 0; i < enumNames.Length; i++)
  603. {
  604. if (subvalue.EqualsOrdinal(enumNames[i]))
  605. {
  606. localResult |= enumValues[i];
  607. success = true;
  608. break;
  609. }
  610. }
  611. }
  612. if (!success)
  613. {
  614. parsed = false;
  615. break;
  616. }
  617. }
  618. if (parsed)
  619. {
  620. result = localResult;
  621. return true;
  622. }
  623. if (throwOnFailure)
  624. {
  625. throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, originalValueString));
  626. }
  627. result = 0;
  628. return false;
  629. }
  630. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  631. private static bool StartsNumber(char c) => char.IsInRange(c, '0', '9') || c == '-' || c == '+';
  632. public static object ToObject(Type enumType, object value)
  633. {
  634. if (value == null)
  635. throw new ArgumentNullException(nameof(value));
  636. // Delegate rest of error checking to the other functions
  637. TypeCode typeCode = Convert.GetTypeCode(value);
  638. return typeCode switch
  639. {
  640. TypeCode.Int32 => ToObject(enumType, (int)value),
  641. TypeCode.SByte => ToObject(enumType, (sbyte)value),
  642. TypeCode.Int16 => ToObject(enumType, (short)value),
  643. TypeCode.Int64 => ToObject(enumType, (long)value),
  644. TypeCode.UInt32 => ToObject(enumType, (uint)value),
  645. TypeCode.Byte => ToObject(enumType, (byte)value),
  646. TypeCode.UInt16 => ToObject(enumType, (ushort)value),
  647. TypeCode.UInt64 => ToObject(enumType, (ulong)value),
  648. TypeCode.Char => ToObject(enumType, (char)value),
  649. TypeCode.Boolean => ToObject(enumType, (bool)value),
  650. _ => throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)),
  651. };
  652. }
  653. public static string Format(Type enumType, object value, string format)
  654. {
  655. RuntimeType rtType = ValidateRuntimeType(enumType);
  656. if (value == null)
  657. throw new ArgumentNullException(nameof(value));
  658. if (format == null)
  659. throw new ArgumentNullException(nameof(format));
  660. // If the value is an Enum then we need to extract the underlying value from it
  661. Type valueType = value.GetType();
  662. if (valueType.IsEnum)
  663. {
  664. if (!valueType.IsEquivalentTo(enumType))
  665. throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType, enumType));
  666. if (format.Length != 1)
  667. {
  668. // all acceptable format string are of length 1
  669. throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
  670. }
  671. return ((Enum)value).ToString(format);
  672. }
  673. // The value must be of the same type as the Underlying type of the Enum
  674. Type underlyingType = GetUnderlyingType(enumType);
  675. if (valueType != underlyingType)
  676. {
  677. throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, valueType, underlyingType));
  678. }
  679. if (format.Length == 1)
  680. {
  681. switch (format[0])
  682. {
  683. case 'G':
  684. case 'g':
  685. return GetEnumName(rtType, ToUInt64(value)) ?? value.ToString()!;
  686. case 'D':
  687. case 'd':
  688. return value.ToString()!;
  689. case 'X':
  690. case 'x':
  691. return ValueToHexString(value);
  692. case 'F':
  693. case 'f':
  694. return InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString()!;
  695. }
  696. }
  697. throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
  698. }
  699. #endregion
  700. #region Private Methods
  701. internal object GetValue()
  702. {
  703. ref byte data = ref this.GetRawData();
  704. return (InternalGetCorElementType()) switch
  705. {
  706. CorElementType.ELEMENT_TYPE_I1 => Unsafe.As<byte, sbyte>(ref data),
  707. CorElementType.ELEMENT_TYPE_U1 => data,
  708. CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As<byte, bool>(ref data),
  709. CorElementType.ELEMENT_TYPE_I2 => Unsafe.As<byte, short>(ref data),
  710. CorElementType.ELEMENT_TYPE_U2 => Unsafe.As<byte, ushort>(ref data),
  711. CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As<byte, char>(ref data),
  712. CorElementType.ELEMENT_TYPE_I4 => Unsafe.As<byte, int>(ref data),
  713. CorElementType.ELEMENT_TYPE_U4 => Unsafe.As<byte, uint>(ref data),
  714. CorElementType.ELEMENT_TYPE_R4 => Unsafe.As<byte, float>(ref data),
  715. CorElementType.ELEMENT_TYPE_I8 => Unsafe.As<byte, long>(ref data),
  716. CorElementType.ELEMENT_TYPE_U8 => Unsafe.As<byte, ulong>(ref data),
  717. CorElementType.ELEMENT_TYPE_R8 => Unsafe.As<byte, double>(ref data),
  718. CorElementType.ELEMENT_TYPE_I => Unsafe.As<byte, IntPtr>(ref data),
  719. CorElementType.ELEMENT_TYPE_U => Unsafe.As<byte, UIntPtr>(ref data),
  720. _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
  721. };
  722. }
  723. private ulong ToUInt64()
  724. {
  725. ref byte data = ref this.GetRawData();
  726. switch (InternalGetCorElementType())
  727. {
  728. case CorElementType.ELEMENT_TYPE_I1:
  729. return (ulong)Unsafe.As<byte, sbyte>(ref data);
  730. case CorElementType.ELEMENT_TYPE_U1:
  731. return data;
  732. case CorElementType.ELEMENT_TYPE_BOOLEAN:
  733. return Convert.ToUInt64(Unsafe.As<byte, bool>(ref data), CultureInfo.InvariantCulture);
  734. case CorElementType.ELEMENT_TYPE_I2:
  735. return (ulong)Unsafe.As<byte, short>(ref data);
  736. case CorElementType.ELEMENT_TYPE_U2:
  737. case CorElementType.ELEMENT_TYPE_CHAR:
  738. return Unsafe.As<byte, ushort>(ref data);
  739. case CorElementType.ELEMENT_TYPE_I4:
  740. return (ulong)Unsafe.As<byte, int>(ref data);
  741. case CorElementType.ELEMENT_TYPE_U4:
  742. case CorElementType.ELEMENT_TYPE_R4:
  743. return Unsafe.As<byte, uint>(ref data);
  744. case CorElementType.ELEMENT_TYPE_I8:
  745. return (ulong)Unsafe.As<byte, long>(ref data);
  746. case CorElementType.ELEMENT_TYPE_U8:
  747. case CorElementType.ELEMENT_TYPE_R8:
  748. return Unsafe.As<byte, ulong>(ref data);
  749. case CorElementType.ELEMENT_TYPE_I:
  750. return (ulong)Unsafe.As<byte, IntPtr>(ref data);
  751. case CorElementType.ELEMENT_TYPE_U:
  752. return (ulong)Unsafe.As<byte, UIntPtr>(ref data);
  753. default:
  754. throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
  755. }
  756. }
  757. #endregion
  758. #region Object Overrides
  759. public override int GetHashCode()
  760. {
  761. // CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type.
  762. // The runtime can bypass calls to Enum::GetHashCode and call the underlying type's GetHashCode directly
  763. // to avoid boxing the enum.
  764. ref byte data = ref this.GetRawData();
  765. return (InternalGetCorElementType()) switch
  766. {
  767. CorElementType.ELEMENT_TYPE_I1 => Unsafe.As<byte, sbyte>(ref data).GetHashCode(),
  768. CorElementType.ELEMENT_TYPE_U1 => data.GetHashCode(),
  769. CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As<byte, bool>(ref data).GetHashCode(),
  770. CorElementType.ELEMENT_TYPE_I2 => Unsafe.As<byte, short>(ref data).GetHashCode(),
  771. CorElementType.ELEMENT_TYPE_U2 => Unsafe.As<byte, ushort>(ref data).GetHashCode(),
  772. CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As<byte, char>(ref data).GetHashCode(),
  773. CorElementType.ELEMENT_TYPE_I4 => Unsafe.As<byte, int>(ref data).GetHashCode(),
  774. CorElementType.ELEMENT_TYPE_U4 => Unsafe.As<byte, uint>(ref data).GetHashCode(),
  775. CorElementType.ELEMENT_TYPE_R4 => Unsafe.As<byte, float>(ref data).GetHashCode(),
  776. CorElementType.ELEMENT_TYPE_I8 => Unsafe.As<byte, long>(ref data).GetHashCode(),
  777. CorElementType.ELEMENT_TYPE_U8 => Unsafe.As<byte, ulong>(ref data).GetHashCode(),
  778. CorElementType.ELEMENT_TYPE_R8 => Unsafe.As<byte, double>(ref data).GetHashCode(),
  779. CorElementType.ELEMENT_TYPE_I => Unsafe.As<byte, IntPtr>(ref data).GetHashCode(),
  780. CorElementType.ELEMENT_TYPE_U => Unsafe.As<byte, UIntPtr>(ref data).GetHashCode(),
  781. _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
  782. };
  783. }
  784. public override string ToString()
  785. {
  786. // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned.
  787. // For PASCAL style enums who's values do not map directly the decimal value of the field is returned.
  788. // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant
  789. // (a pure power of 2), then the OR string (ie "Red, Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of
  790. // pure powers of 2 OR-ed together, you return a hex value
  791. // Try to see if its one of the enum values, then we return a String back else the value
  792. return InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? ValueToString();
  793. }
  794. public int CompareTo(object? target)
  795. {
  796. if (target == this)
  797. return 0;
  798. if (target == null)
  799. return 1; // all values are greater than null
  800. if (GetType() != target.GetType())
  801. throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, target.GetType(), GetType()));
  802. ref byte pThisValue = ref this.GetRawData();
  803. ref byte pTargetValue = ref target.GetRawData();
  804. switch (InternalGetCorElementType())
  805. {
  806. case CorElementType.ELEMENT_TYPE_I1:
  807. return Unsafe.As<byte, sbyte>(ref pThisValue).CompareTo(Unsafe.As<byte, sbyte>(ref pTargetValue));
  808. case CorElementType.ELEMENT_TYPE_U1:
  809. case CorElementType.ELEMENT_TYPE_BOOLEAN:
  810. return pThisValue.CompareTo(pTargetValue);
  811. case CorElementType.ELEMENT_TYPE_I2:
  812. return Unsafe.As<byte, short>(ref pThisValue).CompareTo(Unsafe.As<byte, short>(ref pTargetValue));
  813. case CorElementType.ELEMENT_TYPE_U2:
  814. case CorElementType.ELEMENT_TYPE_CHAR:
  815. return Unsafe.As<byte, ushort>(ref pThisValue).CompareTo(Unsafe.As<byte, ushort>(ref pTargetValue));
  816. case CorElementType.ELEMENT_TYPE_I4:
  817. #if !BIT64
  818. case CorElementType.ELEMENT_TYPE_I:
  819. #endif
  820. return Unsafe.As<byte, int>(ref pThisValue).CompareTo(Unsafe.As<byte, int>(ref pTargetValue));
  821. case CorElementType.ELEMENT_TYPE_U4:
  822. #if !BIT64
  823. case CorElementType.ELEMENT_TYPE_U:
  824. #endif
  825. return Unsafe.As<byte, uint>(ref pThisValue).CompareTo(Unsafe.As<byte, uint>(ref pTargetValue));
  826. case CorElementType.ELEMENT_TYPE_I8:
  827. #if BIT64
  828. case CorElementType.ELEMENT_TYPE_I:
  829. #endif
  830. return Unsafe.As<byte, long>(ref pThisValue).CompareTo(Unsafe.As<byte, long>(ref pTargetValue));
  831. case CorElementType.ELEMENT_TYPE_U8:
  832. #if BIT64
  833. case CorElementType.ELEMENT_TYPE_U:
  834. #endif
  835. return Unsafe.As<byte, ulong>(ref pThisValue).CompareTo(Unsafe.As<byte, ulong>(ref pTargetValue));
  836. case CorElementType.ELEMENT_TYPE_R4:
  837. return Unsafe.As<byte, float>(ref pThisValue).CompareTo(Unsafe.As<byte, float>(ref pTargetValue));
  838. case CorElementType.ELEMENT_TYPE_R8:
  839. return Unsafe.As<byte, double>(ref pThisValue).CompareTo(Unsafe.As<byte, double>(ref pTargetValue));
  840. default:
  841. throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
  842. }
  843. }
  844. #endregion
  845. #region IFormattable
  846. [Obsolete("The provider argument is not used. Please use ToString(String).")]
  847. public string ToString(string? format, IFormatProvider? provider)
  848. {
  849. return ToString(format);
  850. }
  851. #endregion
  852. #region Public Methods
  853. public string ToString(string? format)
  854. {
  855. if (string.IsNullOrEmpty(format))
  856. {
  857. return ToString();
  858. }
  859. if (format.Length == 1)
  860. {
  861. switch (format[0])
  862. {
  863. case 'G':
  864. case 'g':
  865. return ToString();
  866. case 'D':
  867. case 'd':
  868. return ValueToString();
  869. case 'X':
  870. case 'x':
  871. return ValueToHexString();
  872. case 'F':
  873. case 'f':
  874. return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? ValueToString();
  875. }
  876. }
  877. throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
  878. }
  879. [Obsolete("The provider argument is not used. Please use ToString().")]
  880. public string ToString(IFormatProvider? provider)
  881. {
  882. return ToString();
  883. }
  884. #endregion
  885. #region IConvertible
  886. public TypeCode GetTypeCode()
  887. {
  888. return (InternalGetCorElementType()) switch
  889. {
  890. CorElementType.ELEMENT_TYPE_I1 => TypeCode.SByte,
  891. CorElementType.ELEMENT_TYPE_U1 => TypeCode.Byte,
  892. CorElementType.ELEMENT_TYPE_BOOLEAN => TypeCode.Boolean,
  893. CorElementType.ELEMENT_TYPE_I2 => TypeCode.Int16,
  894. CorElementType.ELEMENT_TYPE_U2 => TypeCode.UInt16,
  895. CorElementType.ELEMENT_TYPE_CHAR => TypeCode.Char,
  896. CorElementType.ELEMENT_TYPE_I4 => TypeCode.Int32,
  897. CorElementType.ELEMENT_TYPE_U4 => TypeCode.UInt32,
  898. CorElementType.ELEMENT_TYPE_I8 => TypeCode.Int64,
  899. CorElementType.ELEMENT_TYPE_U8 => TypeCode.UInt64,
  900. _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
  901. };
  902. }
  903. bool IConvertible.ToBoolean(IFormatProvider? provider)
  904. {
  905. return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture);
  906. }
  907. char IConvertible.ToChar(IFormatProvider? provider)
  908. {
  909. return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture);
  910. }
  911. sbyte IConvertible.ToSByte(IFormatProvider? provider)
  912. {
  913. return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture);
  914. }
  915. byte IConvertible.ToByte(IFormatProvider? provider)
  916. {
  917. return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture);
  918. }
  919. short IConvertible.ToInt16(IFormatProvider? provider)
  920. {
  921. return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture);
  922. }
  923. ushort IConvertible.ToUInt16(IFormatProvider? provider)
  924. {
  925. return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture);
  926. }
  927. int IConvertible.ToInt32(IFormatProvider? provider)
  928. {
  929. return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture);
  930. }
  931. uint IConvertible.ToUInt32(IFormatProvider? provider)
  932. {
  933. return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture);
  934. }
  935. long IConvertible.ToInt64(IFormatProvider? provider)
  936. {
  937. return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture);
  938. }
  939. ulong IConvertible.ToUInt64(IFormatProvider? provider)
  940. {
  941. return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture);
  942. }
  943. float IConvertible.ToSingle(IFormatProvider? provider)
  944. {
  945. return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture);
  946. }
  947. double IConvertible.ToDouble(IFormatProvider? provider)
  948. {
  949. return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture);
  950. }
  951. decimal IConvertible.ToDecimal(IFormatProvider? provider)
  952. {
  953. return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture);
  954. }
  955. DateTime IConvertible.ToDateTime(IFormatProvider? provider)
  956. {
  957. throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime"));
  958. }
  959. object IConvertible.ToType(Type type, IFormatProvider? provider)
  960. {
  961. return Convert.DefaultToType((IConvertible)this, type, provider);
  962. }
  963. #endregion
  964. #region ToObject
  965. [CLSCompliant(false)]
  966. public static object ToObject(Type enumType, sbyte value) =>
  967. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  968. public static object ToObject(Type enumType, short value) =>
  969. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  970. public static object ToObject(Type enumType, int value) =>
  971. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  972. public static object ToObject(Type enumType, byte value) =>
  973. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  974. [CLSCompliant(false)]
  975. public static object ToObject(Type enumType, ushort value) =>
  976. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  977. [CLSCompliant(false)]
  978. public static object ToObject(Type enumType, uint value) =>
  979. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  980. public static object ToObject(Type enumType, long value) =>
  981. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  982. [CLSCompliant(false)]
  983. public static object ToObject(Type enumType, ulong value) =>
  984. InternalBoxEnum(ValidateRuntimeType(enumType), unchecked((long)value));
  985. private static object ToObject(Type enumType, char value) =>
  986. InternalBoxEnum(ValidateRuntimeType(enumType), value);
  987. private static object ToObject(Type enumType, bool value) =>
  988. InternalBoxEnum(ValidateRuntimeType(enumType), value ? 1 : 0);
  989. #endregion
  990. }
  991. }