/
Enum.cs
2306 lines (2027 loc) · 137 KB
/
Enum.cs
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.
// Rare enums types not expressible in C# are not supported in native AOT
#if !NATIVEAOT
#define RARE_ENUMS
#endif
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
#pragma warning disable 8500 // Allow taking address of managed types
namespace System
{
/// <summary>Provides the base class for enumerations.</summary>
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract partial class Enum : ValueType, IComparable, ISpanFormattable, IConvertible
{
// Notes:
// - This implementation includes partial support for float/double/nint/nuint-based 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/nint/nuint enums. There was a conscious decision made to not fix the whole stack
// to work well for them because the right behavior is often unclear, and it is hard to test and
// very low value because such enums cannot be expressed in C# and are very rarely encountered.
// - To avoid significant code bloat for public generic APIs, we avoid making the whole implementation
// generic on the enum type (TEnum) all the way through the implementation. Instead, at the public
// entry point we look up the underlying type for that enum, and use that underlying type as the
// generic for the rest of that call tree (TUnderlying). That type is important for controlling
// how the parsing and formatting APIs behave, in particular when parsing and formatting an enum
// value as a number. However, various APIs also need to be able to look up names associated with
// values, and those operations assume the values in the underlying storage are sorted, and for
// integer underlying types, sorted based on the unsigned representation of the underlying value.
// So, for those operations we also or instead pass along a generic for the actual type in which
// the data is stored in the underlying values array (TStorage), which will either be the same
// as the underlying type if the underlying type is not a signed integer, or will be the unsigned
// counterpart to the underlying type if the underlying type is a signed integer. This also has
// the benefit of further limited code bloat, as for the underlying types representable in C#,
// we then only need up to 4 instantiations of some code paths rather than 8.
/// <summary>Character used to separate flag enum values when formatted in a list.</summary>
private const char EnumSeparatorChar = ',';
/// <summary>Retrieves the name of the constant in the specified enumeration type that has the specified value.</summary>
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
/// <param name="value">The value of a particular enumerated constant in terms of its underlying type.</param>
/// <returns>
/// A string containing the name of the enumerated constant in <typeparamref name="TEnum"/> whose value is <paramref name="value"/>,
/// or <see langword="null"/> if no such constant is found.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe string? GetName<TEnum>(TEnum value) where TEnum : struct, Enum
{
RuntimeType rt = (RuntimeType)typeof(TEnum);
Type underlyingType = typeof(TEnum).GetEnumUnderlyingType();
if (underlyingType == typeof(sbyte) || underlyingType == typeof(byte)) return GetNameInlined(GetEnumInfo<byte>(rt), *(byte*)&value);
if (underlyingType == typeof(short) || underlyingType == typeof(ushort)) return GetNameInlined(GetEnumInfo<ushort>(rt), *(ushort*)&value);
if (underlyingType == typeof(int) || underlyingType == typeof(uint)) return GetNameInlined(GetEnumInfo<uint>(rt), *(uint*)&value);
if (underlyingType == typeof(long) || underlyingType == typeof(ulong)) return GetNameInlined(GetEnumInfo<ulong>(rt), *(ulong*)&value);
#if RARE_ENUMS
if (underlyingType == typeof(nint) || underlyingType == typeof(nuint)) return GetNameInlined(GetEnumInfo<nuint>(rt), *(nuint*)&value);
if (underlyingType == typeof(float)) return GetNameInlined(GetEnumInfo<float>(rt), *(float*)&value);
if (underlyingType == typeof(double)) return GetNameInlined(GetEnumInfo<double>(rt), *(double*)&value);
if (underlyingType == typeof(char)) return GetNameInlined(GetEnumInfo<char>(rt), *(char*)&value);
#endif
throw CreateUnknownEnumTypeException();
}
/// <summary>Retrieves the name of the constant in the specified enumeration type that has the specified value.</summary>
/// <param name="enumType">An enumeration type.</param>
/// <param name="value">The value of a particular enumerated constant in terms of its underlying type.</param>
/// <returns>
/// A string containing the name of the enumerated constant in <paramref name="enumType"/> whose value is <paramref name="value"/>,
/// or <see langword="null"/> if no such constant is found.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="enumType"/> or <paramref name="value"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="enumType"/> is not an <see cref="Enum"/>, or <paramref name="value"/> is neither of type <paramref name="enumType"/>
/// nor does it have the same underlying type as <paramref name="enumType"/>.
/// </exception>
public static string? GetName(Type enumType, object value)
{
ArgumentNullException.ThrowIfNull(enumType);
return enumType.GetEnumName(value);
}
/// <summary>Retrieves the name of the constant in the specified enumeration type that has the specified value.</summary>
/// <param name="enumType">An enumeration type.</param>
/// <param name="uint64Value">The value of a particular enumerated constant in terms of its underlying type, cast to a <see cref="ulong"/>.</param>
/// <returns>
/// A string containing the name of the enumerated constant in <paramref name="enumType"/> whose value is <paramref name="uint64Value"/>,
/// or <see langword="null"/> if no such constant is found.
/// </returns>
internal static string? GetName(RuntimeType enumType, ulong uint64Value)
{
// For a given underlying type, validate that the specified ulong is in the range
// of that type. If it's not, it definitely doesn't match. If it is, delegate
// to GetName<TUnderlyingType> to look it up.
Type underlyingType = enumType.GetEnumUnderlyingType();
switch (Type.GetTypeCode(underlyingType)) // can't use InternalGetCorElementType as enumType may actually be the underlying type
{
case TypeCode.SByte:
if ((long)uint64Value < sbyte.MinValue || (long)uint64Value > sbyte.MaxValue) return null;
return GetName(GetEnumInfo<byte>(enumType), (byte)(sbyte)uint64Value);
case TypeCode.Byte:
if (uint64Value > byte.MaxValue) return null;
return GetName(GetEnumInfo<byte>(enumType), (byte)uint64Value);
case TypeCode.Int16:
if ((long)uint64Value < short.MinValue || (long)uint64Value > short.MaxValue) return null;
return GetName(GetEnumInfo<ushort>(enumType), (ushort)(short)uint64Value);
case TypeCode.UInt16:
if (uint64Value > ushort.MaxValue) return null;
return GetName(GetEnumInfo<ushort>(enumType), (ushort)uint64Value);
case TypeCode.Int32:
if ((long)uint64Value < int.MinValue || (long)uint64Value > int.MaxValue) return null;
return GetName(GetEnumInfo<uint>(enumType), (uint)(int)uint64Value);
case TypeCode.UInt32:
if (uint64Value > uint.MaxValue) return null;
return GetName(GetEnumInfo<uint>(enumType), (uint)uint64Value);
case TypeCode.Int64:
return GetName(GetEnumInfo<ulong>(enumType), (ulong)(long)uint64Value);
case TypeCode.UInt64:
return GetName(GetEnumInfo<ulong>(enumType), uint64Value);
#if RARE_ENUMS
case TypeCode.Char:
if (uint64Value > char.MaxValue) return null;
return GetName(GetEnumInfo<char>(enumType), (char)uint64Value);
#endif
};
#if RARE_ENUMS
if (underlyingType == typeof(nint))
{
if ((long)uint64Value < nint.MinValue || (long)uint64Value > nint.MaxValue) return null;
return GetName(GetEnumInfo<nuint>(enumType), (nuint)(nint)uint64Value);
}
if (underlyingType == typeof(nuint))
{
if (uint64Value > nuint.MaxValue) return null;
return GetName(GetEnumInfo<nuint>(enumType), (nuint)uint64Value);
}
#endif
throw CreateUnknownEnumTypeException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string? GetName<TStorage>(EnumInfo<TStorage> enumInfo, TStorage value)
where TStorage : struct, INumber<TStorage> =>
GetNameInlined(enumInfo, value);
/// <summary>Look up the name for the specified underlying value using the cached <see cref="EnumInfo{TStorage}"/> for the associated enum.</summary>
/// <typeparam name="TStorage">The type stored in the EnumInfo. This will either be the same as the underlying type for the enum or its unsigned counterpart if the underlying type is a signed integer.</typeparam>
/// <param name="enumInfo">The cached <see cref="EnumInfo{TStorage}"/> for the enum type.</param>
/// <param name="value">The underlying value for which we're searching.</param>
/// <returns>The name of the value if found; otherwise, <see langword="null"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string? GetNameInlined<TStorage>(EnumInfo<TStorage> enumInfo, TStorage value)
where TStorage : struct, INumber<TStorage>
{
string[] names = enumInfo.Names;
// If the values are known to be sequential starting from 0, then we can simply compare the value
// against the length of the array. The value matches iff it's in-bounds, and if it is, the value
// in the array is where the corresponding name is stored.
if (enumInfo.ValuesAreSequentialFromZero)
{
if (Unsafe.SizeOf<TStorage>() <= sizeof(uint))
{
// Special-case types types that are <= sizeof(int), as we can then eliminate a bounds check on the array.
uint uint32Value = uint.CreateTruncating(value);
if (uint32Value < (uint)names.Length)
{
return names[uint32Value];
}
}
else
{
// Handle the remaining types.
if (ulong.CreateTruncating(value) < (ulong)names.Length)
{
return names[uint.CreateTruncating(value)];
}
}
}
else
{
// Search for the value in the array of values. If we find a non-negative index,
// that's the location of the corresponding name in the names array.
int index = FindDefinedIndex(enumInfo.Values, value);
if ((uint)index < (uint)names.Length)
{
return names[index];
}
}
// Return null so the caller knows no individual named value could be found.
return null;
}
/// <summary>Retrieves an array of the names of the constants in a specified enumeration type.</summary>
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
/// <returns>A string array of the names of the constants in <typeparamref name="TEnum"/>.</returns>
public static string[] GetNames<TEnum>() where TEnum : struct, Enum
{
string[] names;
RuntimeType rt = (RuntimeType)typeof(TEnum);
Type underlyingType = typeof(TEnum).GetEnumUnderlyingType();
// Get the cached names array.
if (underlyingType == typeof(sbyte) || underlyingType == typeof(byte)) names = GetEnumInfo<byte>(rt).Names;
else if (underlyingType == typeof(short) || underlyingType == typeof(ushort)) names = GetEnumInfo<ushort>(rt).Names;
else if (underlyingType == typeof(int) || underlyingType == typeof(uint)) names = GetEnumInfo<uint>(rt).Names;
else if (underlyingType == typeof(long) || underlyingType == typeof(ulong)) names = GetEnumInfo<ulong>(rt).Names;
#if RARE_ENUMS
else if (underlyingType == typeof(nint) || underlyingType == typeof(nuint)) names = GetEnumInfo<nuint>(rt).Names;
else if (underlyingType == typeof(float)) names = GetEnumInfo<float>(rt).Names;
else if (underlyingType == typeof(double)) names = GetEnumInfo<double>(rt).Names;
else if (underlyingType == typeof(char)) names = GetEnumInfo<char>(rt).Names;
#endif
else throw CreateUnknownEnumTypeException();
// Return a clone of the array to avoid exposing the cached array instance.
return new ReadOnlySpan<string>(names).ToArray();
}
/// <summary>Retrieves an array of the names of the constants in a specified enumeration.</summary>
/// <param name="enumType">An enumeration type.</param>
/// <returns>A string array of the names of the constants in <paramref name="enumType"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="enumType"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="enumType"/> is not an <see cref="Enum"/>.</exception>
public static string[] GetNames(Type enumType)
{
ArgumentNullException.ThrowIfNull(enumType);
return enumType.GetEnumNames();
}
/// <summary>Gets the cached names array for the specified enum type, without making a copy.</summary>
/// <remarks>The returned array should not be exposed outside of this assembly.</remarks>
internal static string[] GetNamesNoCopy(RuntimeType enumType)
{
Debug.Assert(enumType.IsActualEnum);
return InternalGetCorElementType(enumType) switch
{
CorElementType.ELEMENT_TYPE_I1 or CorElementType.ELEMENT_TYPE_U1 => GetEnumInfo<byte>(enumType).Names,
CorElementType.ELEMENT_TYPE_I2 or CorElementType.ELEMENT_TYPE_U2 => GetEnumInfo<ushort>(enumType).Names,
CorElementType.ELEMENT_TYPE_I4 or CorElementType.ELEMENT_TYPE_U4 => GetEnumInfo<uint>(enumType).Names,
CorElementType.ELEMENT_TYPE_I8 or CorElementType.ELEMENT_TYPE_U8 => GetEnumInfo<ulong>(enumType).Names,
#if RARE_ENUMS
CorElementType.ELEMENT_TYPE_I or CorElementType.ELEMENT_TYPE_U => GetEnumInfo<nuint>(enumType).Names,
CorElementType.ELEMENT_TYPE_R4 => GetEnumInfo<float>(enumType).Names,
CorElementType.ELEMENT_TYPE_R8 => GetEnumInfo<double>(enumType).Names,
CorElementType.ELEMENT_TYPE_CHAR => GetEnumInfo<char>(enumType).Names,
#endif
_ => throw CreateUnknownEnumTypeException(),
};
}
/// <summary>Returns the underlying type of the specified enumeration.</summary>
/// <param name="enumType">The enumeration whose underlying type will be retrieved.</param>
/// <returns>The underlying type of <paramref name="enumType"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="enumType"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="enumType"/> is not an <see cref="Enum"/>.</exception>
public static Type GetUnderlyingType(Type enumType)
{
ArgumentNullException.ThrowIfNull(enumType);
return enumType.GetEnumUnderlyingType();
}
/// <summary>Retrieves an array of the values of the constants in a specified enumeration type.</summary>
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
/// <returns>An array that contains the values of the constants in <typeparamref name="TEnum"/>.</returns>
public static TEnum[] GetValues<TEnum>() where TEnum : struct, Enum
{
Array values = GetValuesAsUnderlyingTypeNoCopy((RuntimeType)typeof(TEnum));
var result = new TEnum[values.Length];
Array.Copy(values, result, values.Length);
return result;
}
/// <summary>Retrieves an array of the values of the constants in a specified enumeration.</summary>
/// <param name="enumType">An enumeration type.</param>
/// <returns>An array that contains the values of the constants in <paramref name="enumType"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="enumType"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="enumType"/> is not an <see cref="Enum"/>.</exception>
/// <exception cref="InvalidOperationException">
/// The method is invoked by reflection in a reflection-only context, or <paramref name="enumType"/> is a type from an assembly loaded in a reflection-only context.
/// </exception>
[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>
/// You can use this method to get enumeration values when it's hard to create an array of the enumeration type.
/// For example, you might use this method for the <see cref="T:System.Reflection.MetadataLoadContext" /> enumeration or on a platform where run-time code generation is not available.
/// </remarks>
/// <returns>An array that contains the values of the underlying type constants in <typeparamref name="TEnum" />.</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>
/// You can use this method to get enumeration values when it's hard to create an array of the enumeration type.
/// For example, you might use this method for the MetadataLoadContext enumeration or on a platform where run-time code generation is not available.
/// </remarks>
/// <returns>An array that contains the values of the underlying type constants in <paramref name="enumType" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="enumType" /> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="enumType" /> is not an enumeration type.</exception>
public static Array GetValuesAsUnderlyingType(Type enumType)
{
ArgumentNullException.ThrowIfNull(enumType);
return enumType.GetEnumValuesAsUnderlyingType();
}
/// <summary>Retrieves an array of the values of the underlying type constants in a specified enumeration type.</summary>
internal static Array GetValuesAsUnderlyingType(RuntimeType enumType)
{
Debug.Assert(enumType.IsActualEnum);
return InternalGetCorElementType(enumType) switch
{
CorElementType.ELEMENT_TYPE_I1 => GetEnumInfo<byte>(enumType, getNames: false).CloneValues<sbyte>(),
CorElementType.ELEMENT_TYPE_U1 => GetEnumInfo<byte>(enumType, getNames: false).CloneValues<byte>(),
CorElementType.ELEMENT_TYPE_I2 => GetEnumInfo<ushort>(enumType, getNames: false).CloneValues<short>(),
CorElementType.ELEMENT_TYPE_U2 => GetEnumInfo<ushort>(enumType, getNames: false).CloneValues<ushort>(),
CorElementType.ELEMENT_TYPE_I4 => GetEnumInfo<uint>(enumType, getNames: false).CloneValues<int>(),
CorElementType.ELEMENT_TYPE_U4 => GetEnumInfo<uint>(enumType, getNames: false).CloneValues<uint>(),
CorElementType.ELEMENT_TYPE_I8 => GetEnumInfo<ulong>(enumType, getNames: false).CloneValues<long>(),
CorElementType.ELEMENT_TYPE_U8 => GetEnumInfo<ulong>(enumType, getNames: false).CloneValues<ulong>(),
#if RARE_ENUMS
CorElementType.ELEMENT_TYPE_I => GetEnumInfo<nuint>(enumType, getNames: false).CloneValues<nint>(),
CorElementType.ELEMENT_TYPE_U => GetEnumInfo<nuint>(enumType, getNames: false).CloneValues<nuint>(),
CorElementType.ELEMENT_TYPE_R4 => GetEnumInfo<float>(enumType, getNames: false).CloneValues<float>(),
CorElementType.ELEMENT_TYPE_R8 => GetEnumInfo<double>(enumType, getNames: false).CloneValues<double>(),
CorElementType.ELEMENT_TYPE_CHAR => GetEnumInfo<char>(enumType, getNames: false).CloneValues<char>(),
#endif
_ => throw CreateUnknownEnumTypeException(),
};
}
/// <summary>Retrieves the cached array of the values of the underlying type constants in a specified enumeration.</summary>
/// <remarks>
/// The returned array should not be exposed outside of this assembly.
/// It also may be using the corresponding unsigned type if the actual underlying type was signed.
/// </remarks>
internal static Array GetValuesAsUnderlyingTypeNoCopy(RuntimeType enumType)
{
Debug.Assert(enumType.IsActualEnum);
return InternalGetCorElementType(enumType) switch
{
CorElementType.ELEMENT_TYPE_I1 => GetEnumInfo<byte>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_U1 => GetEnumInfo<byte>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_I2 => GetEnumInfo<ushort>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_U2 => GetEnumInfo<ushort>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_I4 => GetEnumInfo<uint>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_U4 => GetEnumInfo<uint>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_I8 => GetEnumInfo<ulong>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_U8 => GetEnumInfo<ulong>(enumType, getNames: false).Values,
#if RARE_ENUMS
CorElementType.ELEMENT_TYPE_I => GetEnumInfo<nuint>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_U => GetEnumInfo<nuint>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_R4 => GetEnumInfo<float>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_R8 => GetEnumInfo<double>(enumType, getNames: false).Values,
CorElementType.ELEMENT_TYPE_CHAR => GetEnumInfo<char>(enumType, getNames: false).Values,
#endif
_ => throw CreateUnknownEnumTypeException(),
};
}
/// <summary>Determines whether one or more bit fields are set in the current instance.</summary>
/// <param name="flag">An enumeration value.</param>
/// <returns><see langword="true"/> if the bit field or bit fields that are set in flag are also set in the current instance; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentException"><paramref name="flag"/> is a different type than the current instance.</exception>
[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:
{
byte flagsValue = pFlagsValue;
return (pThisValue & flagsValue) == flagsValue;
}
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
{
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:
{
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:
{
ulong flagsValue = Unsafe.As<byte, ulong>(ref pFlagsValue);
return (Unsafe.As<byte, ulong>(ref pThisValue) & flagsValue) == flagsValue;
}
#if RARE_ENUMS
case CorElementType.ELEMENT_TYPE_BOOLEAN:
goto case CorElementType.ELEMENT_TYPE_U1;
case CorElementType.ELEMENT_TYPE_CHAR:
goto case CorElementType.ELEMENT_TYPE_U2;
case CorElementType.ELEMENT_TYPE_R4:
goto case CorElementType.ELEMENT_TYPE_U4;
case CorElementType.ELEMENT_TYPE_R8:
goto case CorElementType.ELEMENT_TYPE_U8;
case CorElementType.ELEMENT_TYPE_I:
case CorElementType.ELEMENT_TYPE_U:
#if TARGET_32BIT
goto case CorElementType.ELEMENT_TYPE_U4;
#else
goto case CorElementType.ELEMENT_TYPE_U8;
#endif
#endif
default:
Debug.Fail("Unknown enum underlying type");
return false;
}
}
/// <summary>Returns a <see cref="bool"/> telling whether a given integral value, or its name as a string, exists in a specified enumeration.</summary>
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
/// <param name="value">The value or name of a constant in <typeparamref name="TEnum"/>.</param>
/// <returns><see langword="true"/> if a given integral value exists in a specified enumeration; <see langword="false"/>, otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsDefined<TEnum>(TEnum value) where TEnum : struct, Enum
{
RuntimeType rt = (RuntimeType)typeof(TEnum);
Type underlyingType = typeof(TEnum).GetEnumUnderlyingType();
if (underlyingType == typeof(sbyte) || underlyingType == typeof(byte)) return IsDefinedPrimitive(rt, *(byte*)&value);
if (underlyingType == typeof(short) || underlyingType == typeof(ushort)) return IsDefinedPrimitive(rt, *(ushort*)&value);
if (underlyingType == typeof(int) || underlyingType == typeof(uint)) return IsDefinedPrimitive(rt, *(uint*)&value);
if (underlyingType == typeof(long) || underlyingType == typeof(ulong)) return IsDefinedPrimitive(rt, *(ulong*)&value);
#if RARE_ENUMS
if (underlyingType == typeof(nint) || underlyingType == typeof(nuint)) return IsDefinedPrimitive(rt, *(nuint*)&value);
if (underlyingType == typeof(float)) return IsDefinedPrimitive(rt, *(float*)&value);
if (underlyingType == typeof(double)) return IsDefinedPrimitive(rt, *(double*)&value);
if (underlyingType == typeof(char)) return IsDefinedPrimitive(rt, *(char*)&value);
#endif
throw CreateUnknownEnumTypeException();
}
/// <summary>Gets whether the specified individual value is defined in the specified enum.</summary>
internal static bool IsDefinedPrimitive<TStorage>(RuntimeType enumType, TStorage value)
where TStorage : struct, INumber<TStorage>
{
EnumInfo<TStorage> enumInfo = GetEnumInfo<TStorage>(enumType, getNames: false);
TStorage[] values = enumInfo.Values;
// If the enum's values are all sequentially numbered starting from 0, then we can
// just return if the requested index is in range.
if (enumInfo.ValuesAreSequentialFromZero)
{
return ulong.CreateTruncating(value) < (ulong)values.Length;
}
// Otherwise, search for the value.
return FindDefinedIndex(values, value) >= 0;
}
/// <summary>Returns a <see cref="bool"/> telling whether a given integral value, or its name as a string, exists in a specified enumeration.</summary>
/// <param name="enumType">An enumeration type.</param>
/// <param name="value">The value or name of a constant in <paramref name="enumType"/>.</param>
/// <returns><see langword="true"/> if a constant in <paramref name="enumType"/> has a value equal to value; otherwise, <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="enumType"/> or <paramref name="value"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="enumType"/> is not an <see cref="Enum"/>,
/// or the type of <paramref name="value"/> is an enumeration but it is not an enumeration of type <paramref name="enumType"/>,
/// or the type of <paramref name="value"/> is not an underlying type of <paramref name="enumType"/>.
/// </exception>
public static bool IsDefined(Type enumType, object value)
{
ArgumentNullException.ThrowIfNull(enumType);
return enumType.IsEnumDefined(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int FindDefinedIndex<TStorage>(TStorage[] values, TStorage value)
where TStorage : struct, IEquatable<TStorage>, IComparable<TStorage>
{
// Binary searching has a higher constant overhead than linear searching.
// For smaller enums, use IndexOf.
// For larger enums, use BinarySearch.
const int NumberOfValuesThreshold = 32; // This threshold can be tweaked over time as optimizations evolve.
ReadOnlySpan<TStorage> span = values;
return values.Length <= NumberOfValuesThreshold ?
span.IndexOf(value) :
SpanHelpers.BinarySearch(span, value);
}
/// <summary>Converts the string 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 string containing the name or value to convert.</param>
/// <returns>An <see cref="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, 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 <see cref="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);
/// <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-insensitive.
/// </summary>
/// <param name="enumType">An enumeration type.</param>
/// <param name="value">A string 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 <see cref="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, string value, bool ignoreCase)
{
if (value is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
bool success = TryParse(enumType, value.AsSpan(), ignoreCase, throwOnFailure: true, out object? result);
Debug.Assert(success && result is not null);
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 <see cref="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 && result is not null);
return result;
}
/// <summary>Converts the string 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 string 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="ArgumentNullException"><paramref name="value"/> is <see langword="null"/>.</exception>
/// <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>(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);
/// <summary>
/// Converts the string 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 string 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="ArgumentNullException"><paramref name="value"/> is <see langword="null"/>.</exception>
/// <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>(string value, bool ignoreCase) where TEnum : struct
{
if (value is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
bool success = TryParse(value.AsSpan(), 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(value, ignoreCase, throwOnFailure: true, out TEnum result);
Debug.Assert(success);
return result;
}
/// <summary>Converts the string 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 string 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, 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);
/// <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-insensitive.
/// </summary>
/// <param name="enumType">The enum type to use for parsing.</param>
/// <param name="value">The string 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, string? value, bool ignoreCase, [NotNullWhen(true)] out object? result)
{
if (value is not null)
{
return TryParse(enumType, value.AsSpan(), ignoreCase, throwOnFailure: false, out result);
}
result = null;
return 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.
/// 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);
/// <summary>Core implementation for all non-generic {Try}Parse methods.</summary>
private static unsafe bool TryParse(Type enumType, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, [NotNullWhen(true)] out object? result)
{
bool parsed = false;
long longScratch = 0;
// 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);
switch (InternalGetCorElementType(rt))
{
case CorElementType.ELEMENT_TYPE_I1:
parsed = TryParseByValueOrName<sbyte, byte>(rt, value, ignoreCase, throwOnFailure, out *(sbyte*)&longScratch);
longScratch = *(sbyte*)&longScratch;
break;
case CorElementType.ELEMENT_TYPE_U1:
parsed = TryParseByValueOrName<byte, byte>(rt, value, ignoreCase, throwOnFailure, out *(byte*)&longScratch);
longScratch = *(byte*)&longScratch;
break;
case CorElementType.ELEMENT_TYPE_I2:
parsed = TryParseByValueOrName<short, ushort>(rt, value, ignoreCase, throwOnFailure, out *(short*)&longScratch);
longScratch = *(short*)&longScratch;
break;
case CorElementType.ELEMENT_TYPE_U2:
parsed = TryParseByValueOrName<ushort, ushort>(rt, value, ignoreCase, throwOnFailure, out *(ushort*)&longScratch);
longScratch = *(ushort*)&longScratch;
break;
case CorElementType.ELEMENT_TYPE_I4:
parsed = TryParseByValueOrName<int, uint>(rt, value, ignoreCase, throwOnFailure, out *(int*)&longScratch);
longScratch = *(int*)&longScratch;
break;
case CorElementType.ELEMENT_TYPE_U4:
parsed = TryParseByValueOrName<uint, uint>(rt, value, ignoreCase, throwOnFailure, out *(uint*)&longScratch);
longScratch = *(uint*)&longScratch;
break;
case CorElementType.ELEMENT_TYPE_I8:
parsed = TryParseByValueOrName<long, ulong>(rt, value, ignoreCase, throwOnFailure, out longScratch);
break;
case CorElementType.ELEMENT_TYPE_U8:
parsed = TryParseByValueOrName<ulong, ulong>(rt, value, ignoreCase, throwOnFailure, out *(ulong*)&longScratch);
break;
default:
parsed = TryParseRareTypes(rt, value, ignoreCase, throwOnFailure, out longScratch);
break;
}
result = parsed ? InternalBoxEnum(rt, longScratch) : null;
return parsed;
[MethodImpl(MethodImplOptions.NoInlining)]
static bool TryParseRareTypes(RuntimeType rt, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, [NotNullWhen(true)] out long result)
{
#if RARE_ENUMS
bool parsed;
switch (InternalGetCorElementType(rt))
{
case CorElementType.ELEMENT_TYPE_R4:
{
parsed = TryParseRareTypeByValueOrName<float, float>(rt, value, ignoreCase, throwOnFailure, out float localResult);
result = BitConverter.SingleToInt32Bits(localResult);
}
break;
case CorElementType.ELEMENT_TYPE_R8:
{
parsed = TryParseRareTypeByValueOrName<double, double>(rt, value, ignoreCase, throwOnFailure, out double localResult);
result = BitConverter.DoubleToInt64Bits(localResult);
}
break;
case CorElementType.ELEMENT_TYPE_I:
{
parsed = TryParseRareTypeByValueOrName<nint, nuint>(rt, value, ignoreCase, throwOnFailure, out nint localResult);
result = localResult;
}
break;
case CorElementType.ELEMENT_TYPE_U:
{
parsed = TryParseRareTypeByValueOrName<nuint, nuint>(rt, value, ignoreCase, throwOnFailure, out nuint localResult);
result = (long)localResult;
}
break;
case CorElementType.ELEMENT_TYPE_CHAR:
{
parsed = TryParseRareTypeByValueOrName<char, char>(rt, value, ignoreCase, throwOnFailure, out char localResult);
result = localResult;
}
break;
default:
throw CreateUnknownEnumTypeException();
}
return parsed;
#else
throw CreateUnknownEnumTypeException();
#endif
}
}
/// <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 string 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>([NotNullWhen(true)] string? value, out TEnum result) where TEnum : struct =>
TryParse(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>
/// <typeparam name="TEnum"></typeparam>
/// <param name="value">The span of chars 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(value, ignoreCase: false, 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.
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="value">The string 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>([NotNullWhen(true)] string? value, bool ignoreCase, out TEnum result) where TEnum : struct
{
if (value is not null)
{
return TryParse(value.AsSpan(), ignoreCase, throwOnFailure: false, out result);
}
result = default;
return 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.
/// A parameter specifies whether the operation is case-sensitive.
/// </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(value, ignoreCase, throwOnFailure: false, out result);
/// <summary>Core implementation for all generic {Try}Parse methods.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // compiles to a single call
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) // with IsEnum being an intrinsic, this whole block will be eliminated for all meaningful cases
{
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(TEnum));
}
Unsafe.SkipInit(out result);
RuntimeType rt = (RuntimeType)typeof(TEnum);
Type underlyingType = typeof(TEnum).GetEnumUnderlyingType();
if (underlyingType == typeof(sbyte)) return TryParseByValueOrName<sbyte, byte>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, sbyte>(ref result));
if (underlyingType == typeof(byte)) return TryParseByValueOrName<byte, byte>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, byte>(ref result));
if (underlyingType == typeof(short)) return TryParseByValueOrName<short, ushort>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, short>(ref result));
if (underlyingType == typeof(ushort)) return TryParseByValueOrName<ushort, ushort>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, ushort>(ref result));
if (underlyingType == typeof(int)) return TryParseByValueOrName<int, uint>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, int>(ref result));
if (underlyingType == typeof(uint)) return TryParseByValueOrName<uint, uint>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, uint>(ref result));
if (underlyingType == typeof(long)) return TryParseByValueOrName<long, ulong>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, long>(ref result));
if (underlyingType == typeof(ulong)) return TryParseByValueOrName<ulong, ulong>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, ulong>(ref result));
#if RARE_ENUMS
if (underlyingType == typeof(nint)) return TryParseRareTypeByValueOrName<nint, nuint>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, nint>(ref result));
if (underlyingType == typeof(nuint)) return TryParseRareTypeByValueOrName<nuint, nuint>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, nuint>(ref result));
if (underlyingType == typeof(float)) return TryParseRareTypeByValueOrName<float, float>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, float>(ref result));
if (underlyingType == typeof(double)) return TryParseRareTypeByValueOrName<double, double>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, double>(ref result));
if (underlyingType == typeof(char)) return TryParseRareTypeByValueOrName<char, char>(rt, value, ignoreCase, throwOnFailure, out Unsafe.As<TEnum, char>(ref result));
#endif
throw CreateUnknownEnumTypeException();
}
/// <summary>Core implementation for all {Try}Parse methods, both generic and non-generic, parsing either by value or by name.</summary>
private static unsafe bool TryParseByValueOrName<TUnderlying, TStorage>(
RuntimeType enumType, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out TUnderlying result)
where TUnderlying : unmanaged, IBinaryIntegerParseAndFormatInfo<TUnderlying>
where TStorage : unmanaged, IBinaryIntegerParseAndFormatInfo<TStorage>
{
AssertValidGenerics<TUnderlying, TStorage>();
if (!value.IsEmpty)
{
char c = value[0];
if (char.IsWhiteSpace(c))
{
value = value.TrimStart();
if (value.IsEmpty)
{
goto ParseFailure;
}
c = value[0];
}
if (!char.IsAsciiDigit(c) && c != '-' && c != '+')
{
Unsafe.SkipInit(out result);
return TryParseByName(enumType, value, ignoreCase, throwOnFailure, out Unsafe.As<TUnderlying, TStorage>(ref result));
}
NumberFormatInfo numberFormat = CultureInfo.InvariantCulture.NumberFormat;
const NumberStyles NumberStyle = NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingWhite;
Number.ParsingStatus status = Number.TryParseBinaryIntegerStyle(value, NumberStyle, numberFormat, out result);
if (status == Number.ParsingStatus.OK)
{
return true;
}
if (status != Number.ParsingStatus.Overflow)
{
Unsafe.SkipInit(out result);
return TryParseByName(enumType, value, ignoreCase, throwOnFailure, out Unsafe.As<TUnderlying, TStorage>(ref result));
}
if (throwOnFailure)
{
Number.ThrowOverflowException<TUnderlying>();
}
}
ParseFailure:
if (throwOnFailure)
{
ThrowInvalidEmptyParseArgument();
}
result = default;
return false;
}
private static unsafe bool TryParseRareTypeByValueOrName<TUnderlying, TStorage>(
RuntimeType enumType, ReadOnlySpan<char> value, bool ignoreCase, bool throwOnFailure, out TUnderlying result)
where TUnderlying : struct, INumber<TUnderlying>, IBitwiseOperators<TUnderlying, TUnderlying, TUnderlying>, IMinMaxValue<TUnderlying>
where TStorage : struct, INumber<TStorage>, IBitwiseOperators<TStorage, TStorage, TStorage>, IMinMaxValue<TStorage>
{
AssertValidGenerics<TUnderlying, TStorage>();
if (!value.IsEmpty)
{
char c = value[0];
if (char.IsWhiteSpace(c))
{
value = value.TrimStart();
if (value.IsEmpty)
{
goto ParseFailure;
}
c = value[0];
}
if (!char.IsAsciiDigit(c) && c != '-' && c != '+')
{
Unsafe.SkipInit(out result);
return TryParseByName(enumType, value, ignoreCase, throwOnFailure, out Unsafe.As<TUnderlying, TStorage>(ref result));
}
#if RARE_ENUMS