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