summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/RtType.cs
blob: ef3ba297876258c1175eca921f643862145be83a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//
//
//
// Implements System.RuntimeType
//
// ======================================================================================


using System;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Runtime.Remoting;
using MdSigCallingConvention = System.Signature.MdSigCallingConvention;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
using System.Runtime.InteropServices;
using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute;
using MdToken = System.Reflection.MetadataToken;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;

namespace System
{
    // this is a work around to get the concept of a calli. It's not as fast but it would be interesting to 
    // see how it compares to the current implementation. 
    // This delegate will disappear at some point in favor of calli 

    internal delegate void CtorDelegate(Object instance);

    // Keep this in sync with FormatFlags defined in typestring.h
    internal enum TypeNameFormatFlags
    {
        FormatBasic = 0x00000000, // Not a bitmask, simply the tersest flag settings possible
        FormatNamespace = 0x00000001, // Include namespace and/or enclosing class names in type names
        FormatFullInst = 0x00000002, // Include namespace and assembly in generic types (regardless of other flag settings)
        FormatAssembly = 0x00000004, // Include assembly display name in type names
        FormatSignature = 0x00000008, // Include signature in method names
        FormatNoVersion = 0x00000010, // Suppress version and culture information in all assembly names
#if _DEBUG
        FormatDebug = 0x00000020, // For debug printing of types only
#endif
        FormatAngleBrackets = 0x00000040, // Whether generic types are C<T> or C[T]
        FormatStubInfo = 0x00000080, // Include stub info like {unbox-stub}
        FormatGenericParam = 0x00000100, // Use !name and !!name for generic type and method parameters

        // If we want to be able to distinguish between overloads whose parameter types have the same name but come from different assemblies,
        // we can add FormatAssembly | FormatNoVersion to FormatSerialization. But we are omitting it because it is not a useful scenario
        // and including the assembly name will normally increase the size of the serialized data and also decrease the performance.
        FormatSerialization = FormatNamespace |
                              FormatGenericParam |
                              FormatFullInst
    }

    internal enum TypeNameKind
    {
        Name,
        ToString,
        SerializationName,
        FullName,
    }

    [Serializable]
    internal class RuntimeType :
        System.Reflection.TypeInfo, ISerializable, ICloneable
    {
        #region Definitions

        internal enum MemberListType
        {
            All,
            CaseSensitive,
            CaseInsensitive,
            HandleToInfo
        }

        // Helper to build lists of MemberInfos. Special cased to avoid allocations for lists of one element.
        private struct ListBuilder<T> where T : class
        {
            private T[] _items;
            private T _item;
            private int _count;
            private int _capacity;

            public ListBuilder(int capacity)
            {
                _items = null;
                _item = null;
                _count = 0;
                _capacity = capacity;
            }

            public T this[int index]
            {
                get
                {
                    Contract.Requires(index < Count);
                    return (_items != null) ? _items[index] : _item;
                }
            }

            public T[] ToArray()
            {
                if (_count == 0)
                    return Array.Empty<T>();
                if (_count == 1)
                    return new T[1] { _item };

                Array.Resize(ref _items, _count);
                _capacity = _count;
                return _items;
            }

            public void CopyTo(Object[] array, int index)
            {
                if (_count == 0)
                    return;

                if (_count == 1)
                {
                    array[index] = _item;
                    return;
                }

                Array.Copy(_items, 0, array, index, _count);
            }

            public int Count
            {
                get
                {
                    return _count;
                }
            }

            public void Add(T item)
            {
                if (_count == 0)
                {
                    _item = item;
                }
                else
                {
                    if (_count == 1)
                    {
                        if (_capacity < 2)
                            _capacity = 4;
                        _items = new T[_capacity];
                        _items[0] = _item;
                    }
                    else
                    if (_capacity == _count)
                    {
                        int newCapacity = 2 * _capacity;
                        Array.Resize(ref _items, newCapacity);
                        _capacity = newCapacity;
                    }

                    _items[_count] = item;
                }
                _count++;
            }
        }

        internal class RuntimeTypeCache
        {
            private const int MAXNAMELEN = 1024;

            #region Definitions
            internal enum CacheType
            {
                Method,
                Constructor,
                Field,
                Property,
                Event,
                Interface,
                NestedType
            }

            private struct Filter
            {
                private Utf8String m_name;
                private MemberListType m_listType;
                private uint m_nameHash;

                public unsafe Filter(byte* pUtf8Name, int cUtf8Name, MemberListType listType)
                {
                    m_name = new Utf8String((void*)pUtf8Name, cUtf8Name);
                    m_listType = listType;
                    m_nameHash = 0;

                    if (RequiresStringComparison())
                    {
                        m_nameHash = m_name.HashCaseInsensitive();
                    }
                }

                public bool Match(Utf8String name)
                {
                    bool retVal = true;

                    if (m_listType == MemberListType.CaseSensitive)
                        retVal = m_name.Equals(name);
                    else if (m_listType == MemberListType.CaseInsensitive)
                        retVal = m_name.EqualsCaseInsensitive(name);

                    // Currently the callers of UsesStringComparison assume that if it returns false
                    // then the match always succeeds and can be skipped.  Assert that this is maintained.
                    Debug.Assert(retVal || RequiresStringComparison());

                    return retVal;
                }

                // Does the current match type require a string comparison?
                // If not, we know Match will always return true and the call can be skipped
                // If so, we know we can have a valid hash to check against from GetHashToMatch
                public bool RequiresStringComparison()
                {
                    return (m_listType == MemberListType.CaseSensitive) ||
                           (m_listType == MemberListType.CaseInsensitive);
                }

                public bool CaseSensitive()
                {
                    return (m_listType == MemberListType.CaseSensitive);
                }

                public uint GetHashToMatch()
                {
                    Debug.Assert(RequiresStringComparison());

                    return m_nameHash;
                }
            }

            private class MemberInfoCache<T> where T : MemberInfo
            {
                #region Private Data Members

                // MemberInfo caches
                private CerHashtable<string, T[]> m_csMemberInfos;
                private CerHashtable<string, T[]> m_cisMemberInfos;
                // List of MemberInfos given out. When m_cacheComplete is false, it may have null entries at the end to avoid
                // reallocating the list every time a new entry is added.
                private T[] m_allMembers;
                private bool m_cacheComplete;

                // This is the strong reference back to the cache
                private RuntimeTypeCache m_runtimeTypeCache;
                #endregion

                #region Constructor
#if MDA_SUPPORTED
#endif
                internal MemberInfoCache(RuntimeTypeCache runtimeTypeCache)
                {
#if MDA_SUPPORTED
                    Mda.MemberInfoCacheCreation();
#endif
                    m_runtimeTypeCache = runtimeTypeCache;
                }

                internal MethodBase AddMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method, CacheType cacheType)
                {
                    T[] list = null;
                    MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(method);
                    bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public;
                    bool isStatic = (methodAttributes & MethodAttributes.Static) != 0;
                    bool isInherited = declaringType != ReflectedType;
                    BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
                    switch (cacheType)
                    {
                        case CacheType.Method:
                            list = (T[])(object)new RuntimeMethodInfo[1] {
                            new RuntimeMethodInfo(method, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags, null)
                        };
                            break;
                        case CacheType.Constructor:
                            list = (T[])(object)new RuntimeConstructorInfo[1] {
                            new RuntimeConstructorInfo(method, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags)
                        };
                            break;
                    }

                    Insert(ref list, null, MemberListType.HandleToInfo);

                    return (MethodBase)(object)list[0];
                }

                internal FieldInfo AddField(RuntimeFieldHandleInternal field)
                {
                    // create the runtime field info
                    FieldAttributes fieldAttributes = RuntimeFieldHandle.GetAttributes(field);
                    bool isPublic = (fieldAttributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public;
                    bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0;
                    RuntimeType approxDeclaringType = RuntimeFieldHandle.GetApproxDeclaringType(field);
                    bool isInherited = RuntimeFieldHandle.AcquiresContextFromThis(field) ?
                        !RuntimeTypeHandle.CompareCanonicalHandles(approxDeclaringType, ReflectedType) :
                        approxDeclaringType != ReflectedType;

                    BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);

                    T[] list = (T[])(object)new RuntimeFieldInfo[1] {
                        new RtFieldInfo(field, ReflectedType, m_runtimeTypeCache, bindingFlags)
                    };

                    Insert(ref list, null, MemberListType.HandleToInfo);

                    return (FieldInfo)(object)list[0];
                }

                private unsafe T[] Populate(string name, MemberListType listType, CacheType cacheType)
                {
                    T[] list = null;

                    if (name == null || name.Length == 0 ||
                        (cacheType == CacheType.Constructor && name.FirstChar != '.' && name.FirstChar != '*'))
                    {
                        list = GetListByName(null, 0, null, 0, listType, cacheType);
                    }
                    else
                    {
                        int cNameLen = name.Length;
                        fixed (char* pName = name)
                        {
                            int cUtf8Name = Encoding.UTF8.GetByteCount(pName, cNameLen);
                            // allocating on the stack is faster than allocating on the GC heap
                            // but we surely don't want to cause a stack overflow
                            // no one should be looking for a member whose name is longer than 1024
                            if (cUtf8Name > MAXNAMELEN)
                            {
                                byte[] utf8Name = new byte[cUtf8Name];
                                fixed (byte* pUtf8Name = &utf8Name[0])
                                {
                                    list = GetListByName(pName, cNameLen, pUtf8Name, cUtf8Name, listType, cacheType);
                                }
                            }
                            else
                            {
                                byte* pUtf8Name = stackalloc byte[cUtf8Name];
                                list = GetListByName(pName, cNameLen, pUtf8Name, cUtf8Name, listType, cacheType);
                            }
                        }
                    }

                    Insert(ref list, name, listType);

                    return list;
                }

                private unsafe T[] GetListByName(char* pName, int cNameLen, byte* pUtf8Name, int cUtf8Name, MemberListType listType, CacheType cacheType)
                {
                    if (cNameLen != 0)
                        Encoding.UTF8.GetBytes(pName, cNameLen, pUtf8Name, cUtf8Name);

                    Filter filter = new Filter(pUtf8Name, cUtf8Name, listType);
                    Object list = null;

                    switch (cacheType)
                    {
                        case CacheType.Method:
                            list = PopulateMethods(filter);
                            break;
                        case CacheType.Field:
                            list = PopulateFields(filter);
                            break;
                        case CacheType.Constructor:
                            list = PopulateConstructors(filter);
                            break;
                        case CacheType.Property:
                            list = PopulateProperties(filter);
                            break;
                        case CacheType.Event:
                            list = PopulateEvents(filter);
                            break;
                        case CacheType.NestedType:
                            list = PopulateNestedClasses(filter);
                            break;
                        case CacheType.Interface:
                            list = PopulateInterfaces(filter);
                            break;
                        default:
                            BCLDebug.Assert(false, "Invalid CacheType");
                            break;
                    }

                    return (T[])list;
                }

                // May replace the list with a new one if certain cache
                // lookups succeed.  Also, may modify the contents of the list
                // after merging these new data structures with cached ones.
                internal void Insert(ref T[] list, string name, MemberListType listType)
                {
                    bool lockTaken = false;

                    RuntimeHelpers.PrepareConstrainedRegions();
                    try
                    {
                        Monitor.Enter(this, ref lockTaken);

                        switch (listType)
                        {
                            case MemberListType.CaseSensitive:
                                {
                                    // Ensure we always return a list that has 
                                    // been merged with the global list.
                                    T[] cachedList = m_csMemberInfos[name];
                                    if (cachedList == null)
                                    {
                                        MergeWithGlobalList(list);
                                        m_csMemberInfos[name] = list;
                                    }
                                    else
                                        list = cachedList;
                                }
                                break;

                            case MemberListType.CaseInsensitive:
                                {
                                    // Ensure we always return a list that has 
                                    // been merged with the global list.
                                    T[] cachedList = m_cisMemberInfos[name];
                                    if (cachedList == null)
                                    {
                                        MergeWithGlobalList(list);
                                        m_cisMemberInfos[name] = list;
                                    }
                                    else
                                        list = cachedList;
                                }
                                break;

                            case MemberListType.All:
                                if (!m_cacheComplete)
                                {
                                    MergeWithGlobalList(list);

                                    // Trim null entries at the end of m_allMembers array
                                    int memberCount = m_allMembers.Length;
                                    while (memberCount > 0)
                                    {
                                        if (m_allMembers[memberCount - 1] != null)
                                            break;
                                        memberCount--;
                                    }
                                    Array.Resize(ref m_allMembers, memberCount);

                                    Volatile.Write(ref m_cacheComplete, true);
                                }
                                else
                                    list = m_allMembers;
                                break;

                            default:
                                MergeWithGlobalList(list);
                                break;
                        }
                    }
                    finally
                    {
                        if (lockTaken)
                        {
                            Monitor.Exit(this);
                        }
                    }
                }

                // Modifies the existing list.
                private void MergeWithGlobalList(T[] list)
                {
                    T[] cachedMembers = m_allMembers;

                    if (cachedMembers == null)
                    {
                        m_allMembers = list;
                        return;
                    }

                    int cachedCount = cachedMembers.Length;
                    int freeSlotIndex = 0;

                    for (int i = 0; i < list.Length; i++)
                    {
                        T newMemberInfo = list[i];
                        bool foundInCache = false;

                        int cachedIndex;
                        for (cachedIndex = 0; cachedIndex < cachedCount; cachedIndex++)
                        {
                            T cachedMemberInfo = cachedMembers[cachedIndex];
                            if (cachedMemberInfo == null)
                                break;

                            if (newMemberInfo.CacheEquals(cachedMemberInfo))
                            {
                                list[i] = cachedMemberInfo;
                                foundInCache = true;
                                break;
                            }
                        }

                        if (!foundInCache)
                        {
                            if (freeSlotIndex == 0)
                                freeSlotIndex = cachedIndex;

                            if (freeSlotIndex >= cachedMembers.Length)
                            {
                                int newSize;
                                if (m_cacheComplete)
                                {
                                    //
                                    // In theory, we should never add more elements to the cache when it is complete.
                                    //
                                    // Unfortunately, we shipped with bugs that cause changes of the complete cache (DevDiv #339308).
                                    // Grow the list by exactly one element in this case to avoid null entries at the end.
                                    //

                                    Debug.Assert(false);

                                    newSize = cachedMembers.Length + 1;
                                }
                                else
                                {
                                    newSize = Math.Max(Math.Max(4, 2 * cachedMembers.Length), list.Length);
                                }

                                // Use different variable for ref argument to Array.Resize to allow enregistration of cachedMembers by the JIT
                                T[] cachedMembers2 = cachedMembers;
                                Array.Resize(ref cachedMembers2, newSize);
                                cachedMembers = cachedMembers2;
                            }

                            Debug.Assert(cachedMembers[freeSlotIndex] == null);
                            cachedMembers[freeSlotIndex] = newMemberInfo;
                            freeSlotIndex++;
                        }
                    }

                    m_allMembers = cachedMembers;
                }
                #endregion

                #region Population Logic

                private unsafe RuntimeMethodInfo[] PopulateMethods(Filter filter)
                {
                    ListBuilder<RuntimeMethodInfo> list = new ListBuilder<RuntimeMethodInfo>();

                    RuntimeType declaringType = ReflectedType;
                    Debug.Assert(declaringType != null);

                    if (RuntimeTypeHandle.IsInterface(declaringType))
                    {
                        #region IsInterface

                        foreach (RuntimeMethodHandleInternal methodHandle in RuntimeTypeHandle.GetIntroducedMethods(declaringType))
                        {
                            if (filter.RequiresStringComparison())
                            {
                                if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
                                {
                                    Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
                                    continue;
                                }

                                if (!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)))
                                    continue;
                            }

                            #region Loop through all methods on the interface
                            Debug.Assert(!methodHandle.IsNullHandle());
                            // Except for .ctor, .cctor, IL_STUB*, and static methods, all interface methods should be abstract, virtual, and non-RTSpecialName.
                            // Note that this assumption will become invalid when we add support for non-abstract or static methods on interfaces.
                            Debug.Assert(
                                (RuntimeMethodHandle.GetAttributes(methodHandle) & (MethodAttributes.RTSpecialName | MethodAttributes.Abstract | MethodAttributes.Virtual)) == (MethodAttributes.Abstract | MethodAttributes.Virtual) ||
                                (RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.Static) == MethodAttributes.Static ||
                                RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
                                RuntimeMethodHandle.GetName(methodHandle).Equals(".cctor") ||
                                RuntimeMethodHandle.GetName(methodHandle).StartsWith("IL_STUB", StringComparison.Ordinal));

                            #region Calculate Binding Flags
                            MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
                            bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public;
                            bool isStatic = (methodAttributes & MethodAttributes.Static) != 0;
                            bool isInherited = false;
                            BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
                            #endregion

                            if ((methodAttributes & MethodAttributes.RTSpecialName) != 0)
                                continue;

                            // get the unboxing stub or instantiating stub if needed
                            RuntimeMethodHandleInternal instantiatedHandle = RuntimeMethodHandle.GetStubIfNeeded(methodHandle, declaringType, null);

                            RuntimeMethodInfo runtimeMethodInfo = new RuntimeMethodInfo(
                            instantiatedHandle, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags, null);

                            list.Add(runtimeMethodInfo);
                            #endregion  
                        }
                        #endregion
                    }
                    else
                    {
                        #region IsClass or GenericParameter
                        while (RuntimeTypeHandle.IsGenericVariable(declaringType))
                            declaringType = declaringType.GetBaseType();

                        bool* overrides = stackalloc bool[RuntimeTypeHandle.GetNumVirtuals(declaringType)];
                        bool isValueType = declaringType.IsValueType;

                        do
                        {
                            int vtableSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);

                            foreach (RuntimeMethodHandleInternal methodHandle in RuntimeTypeHandle.GetIntroducedMethods(declaringType))
                            {
                                if (filter.RequiresStringComparison())
                                {
                                    if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
                                    {
                                        Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
                                        continue;
                                    }

                                    if (!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)))
                                        continue;
                                }

                                #region Loop through all methods on the current type
                                Debug.Assert(!methodHandle.IsNullHandle());

                                MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);
                                MethodAttributes methodAccess = methodAttributes & MethodAttributes.MemberAccessMask;

                                #region Continue if this is a constructor
                                Debug.Assert(
                                    (RuntimeMethodHandle.GetAttributes(methodHandle) & MethodAttributes.RTSpecialName) == 0 ||
                                    RuntimeMethodHandle.GetName(methodHandle).Equals(".ctor") ||
                                    RuntimeMethodHandle.GetName(methodHandle).Equals(".cctor"));

                                if ((methodAttributes & MethodAttributes.RTSpecialName) != 0)
                                    continue;
                                #endregion

                                #region Continue if this is a private declared on a base type
                                bool isVirtual = false;
                                int methodSlot = 0;
                                if ((methodAttributes & MethodAttributes.Virtual) != 0)
                                {
                                    // only virtual if actually in the vtableslot range, but GetSlot will
                                    // assert if an EnC method, which can't be virtual, so narrow down first
                                    // before calling GetSlot
                                    methodSlot = RuntimeMethodHandle.GetSlot(methodHandle);
                                    isVirtual = (methodSlot < vtableSlots);
                                }

                                bool isInherited = declaringType != ReflectedType;

                                bool isPrivate = methodAccess == MethodAttributes.Private;
                                if (isInherited && isPrivate && !isVirtual)
                                    continue;

                                #endregion

                                #region Continue if this is a virtual and is already overridden
                                if (isVirtual)
                                {
                                    Debug.Assert(
                                        (methodAttributes & MethodAttributes.Abstract) != 0 ||
                                        (methodAttributes & MethodAttributes.Virtual) != 0 ||
                                        RuntimeMethodHandle.GetDeclaringType(methodHandle) != declaringType);

                                    if (overrides[methodSlot] == true)
                                        continue;

                                    overrides[methodSlot] = true;
                                }
                                else if (isValueType)
                                {
                                    if ((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) != 0)
                                        continue;
                                }
                                else
                                {
                                    Debug.Assert((methodAttributes & (MethodAttributes.Virtual | MethodAttributes.Abstract)) == 0);
                                }
                                #endregion

                                #region Calculate Binding Flags
                                bool isPublic = methodAccess == MethodAttributes.Public;
                                bool isStatic = (methodAttributes & MethodAttributes.Static) != 0;
                                BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
                                #endregion

                                // get the unboxing stub or instantiating stub if needed
                                RuntimeMethodHandleInternal instantiatedHandle = RuntimeMethodHandle.GetStubIfNeeded(methodHandle, declaringType, null);

                                RuntimeMethodInfo runtimeMethodInfo = new RuntimeMethodInfo(
                                instantiatedHandle, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags, null);

                                list.Add(runtimeMethodInfo);
                                #endregion
                            }

                            declaringType = RuntimeTypeHandle.GetBaseType(declaringType);
                        } while (declaringType != null);
                        #endregion
                    }

                    return list.ToArray();
                }

                private RuntimeConstructorInfo[] PopulateConstructors(Filter filter)
                {
                    if (ReflectedType.IsGenericParameter)
                    {
                        return Array.Empty<RuntimeConstructorInfo>();
                    }

                    ListBuilder<RuntimeConstructorInfo> list = new ListBuilder<RuntimeConstructorInfo>();

                    RuntimeType declaringType = ReflectedType;

                    foreach (RuntimeMethodHandleInternal methodHandle in RuntimeTypeHandle.GetIntroducedMethods(declaringType))
                    {
                        if (filter.RequiresStringComparison())
                        {
                            if (!RuntimeMethodHandle.MatchesNameHash(methodHandle, filter.GetHashToMatch()))
                            {
                                Debug.Assert(!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)));
                                continue;
                            }

                            if (!filter.Match(RuntimeMethodHandle.GetUtf8Name(methodHandle)))
                                continue;
                        }

                        MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(methodHandle);

                        Debug.Assert(!methodHandle.IsNullHandle());

                        if ((methodAttributes & MethodAttributes.RTSpecialName) == 0)
                            continue;

                        // Constructors should not be virtual or abstract
                        Debug.Assert(
                            (methodAttributes & MethodAttributes.Abstract) == 0 &&
                            (methodAttributes & MethodAttributes.Virtual) == 0);

                        #region Calculate Binding Flags
                        bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public;
                        bool isStatic = (methodAttributes & MethodAttributes.Static) != 0;
                        bool isInherited = false;
                        BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
                        #endregion

                        // get the unboxing stub or instantiating stub if needed
                        RuntimeMethodHandleInternal instantiatedHandle = RuntimeMethodHandle.GetStubIfNeeded(methodHandle, declaringType, null);

                        RuntimeConstructorInfo runtimeConstructorInfo =
                        new RuntimeConstructorInfo(instantiatedHandle, ReflectedType, m_runtimeTypeCache, methodAttributes, bindingFlags);

                        list.Add(runtimeConstructorInfo);
                    }

                    return list.ToArray();
                }

                private unsafe RuntimeFieldInfo[] PopulateFields(Filter filter)
                {
                    ListBuilder<RuntimeFieldInfo> list = new ListBuilder<RuntimeFieldInfo>();

                    RuntimeType declaringType = ReflectedType;

                    #region Populate all static, instance and literal fields
                    while (RuntimeTypeHandle.IsGenericVariable(declaringType))
                        declaringType = declaringType.GetBaseType();

                    while (declaringType != null)
                    {
                        PopulateRtFields(filter, declaringType, ref list);

                        PopulateLiteralFields(filter, declaringType, ref list);

                        declaringType = RuntimeTypeHandle.GetBaseType(declaringType);
                    }
                    #endregion

                    #region Populate Literal Fields on Interfaces
                    if (ReflectedType.IsGenericParameter)
                    {
                        Type[] interfaces = ReflectedType.BaseType.GetInterfaces();

                        for (int i = 0; i < interfaces.Length; i++)
                        {
                            // Populate literal fields defined on any of the interfaces implemented by the declaring type
                            PopulateLiteralFields(filter, (RuntimeType)interfaces[i], ref list);
                            PopulateRtFields(filter, (RuntimeType)interfaces[i], ref list);
                        }
                    }
                    else
                    {
                        Type[] interfaces = RuntimeTypeHandle.GetInterfaces(ReflectedType);

                        if (interfaces != null)
                        {
                            for (int i = 0; i < interfaces.Length; i++)
                            {
                                // Populate literal fields defined on any of the interfaces implemented by the declaring type
                                PopulateLiteralFields(filter, (RuntimeType)interfaces[i], ref list);
                                PopulateRtFields(filter, (RuntimeType)interfaces[i], ref list);
                            }
                        }
                    }
                    #endregion

                    return list.ToArray();
                }

                private unsafe void PopulateRtFields(Filter filter, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
                {
                    IntPtr* pResult = stackalloc IntPtr[64];
                    int count = 64;

                    if (!RuntimeTypeHandle.GetFields(declaringType, pResult, &count))
                    {
                        fixed (IntPtr* pBigResult = new IntPtr[count])
                        {
                            RuntimeTypeHandle.GetFields(declaringType, pBigResult, &count);
                            PopulateRtFields(filter, pBigResult, count, declaringType, ref list);
                        }
                    }
                    else if (count > 0)
                    {
                        PopulateRtFields(filter, pResult, count, declaringType, ref list);
                    }
                }

                private unsafe void PopulateRtFields(Filter filter,
                    IntPtr* ppFieldHandles, int count, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
                {
                    Contract.Requires(declaringType != null);
                    Contract.Requires(ReflectedType != null);

                    bool needsStaticFieldForGeneric = RuntimeTypeHandle.HasInstantiation(declaringType) && !RuntimeTypeHandle.ContainsGenericVariables(declaringType);
                    bool isInherited = declaringType != ReflectedType;

                    for (int i = 0; i < count; i++)
                    {
                        RuntimeFieldHandleInternal runtimeFieldHandle = new RuntimeFieldHandleInternal(ppFieldHandles[i]);

                        if (filter.RequiresStringComparison())
                        {
                            if (!RuntimeFieldHandle.MatchesNameHash(runtimeFieldHandle, filter.GetHashToMatch()))
                            {
                                Debug.Assert(!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)));
                                continue;
                            }

                            if (!filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandle)))
                                continue;
                        }

                        Debug.Assert(!runtimeFieldHandle.IsNullHandle());

                        FieldAttributes fieldAttributes = RuntimeFieldHandle.GetAttributes(runtimeFieldHandle);
                        FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask;

                        if (isInherited)
                        {
                            if (fieldAccess == FieldAttributes.Private)
                                continue;
                        }

                        #region Calculate Binding Flags
                        bool isPublic = fieldAccess == FieldAttributes.Public;
                        bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0;
                        BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
                        #endregion

                        // correct the FieldDesc if needed
                        if (needsStaticFieldForGeneric && isStatic)
                            runtimeFieldHandle = RuntimeFieldHandle.GetStaticFieldForGenericType(runtimeFieldHandle, declaringType);

                        RuntimeFieldInfo runtimeFieldInfo =
                            new RtFieldInfo(runtimeFieldHandle, declaringType, m_runtimeTypeCache, bindingFlags);

                        list.Add(runtimeFieldInfo);
                    }
                }

                private unsafe void PopulateLiteralFields(Filter filter, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
                {
                    Contract.Requires(declaringType != null);
                    Contract.Requires(ReflectedType != null);

                    int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType);

                    // Our policy is that TypeDescs do not have metadata tokens
                    if (MdToken.IsNullToken(tkDeclaringType))
                        return;

                    MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(declaringType);

                    MetadataEnumResult tkFields;
                    scope.EnumFields(tkDeclaringType, out tkFields);

                    for (int i = 0; i < tkFields.Length; i++)
                    {
                        int tkField = tkFields[i];
                        Debug.Assert(MdToken.IsTokenOfType(tkField, MetadataTokenType.FieldDef));
                        Debug.Assert(!MdToken.IsNullToken(tkField));

                        FieldAttributes fieldAttributes;
                        scope.GetFieldDefProps(tkField, out fieldAttributes);

                        FieldAttributes fieldAccess = fieldAttributes & FieldAttributes.FieldAccessMask;

                        if ((fieldAttributes & FieldAttributes.Literal) != 0)
                        {
                            bool isInherited = declaringType != ReflectedType;
                            if (isInherited)
                            {
                                bool isPrivate = fieldAccess == FieldAttributes.Private;
                                if (isPrivate)
                                    continue;
                            }

                            if (filter.RequiresStringComparison())
                            {
                                Utf8String name;
                                name = scope.GetName(tkField);

                                if (!filter.Match(name))
                                    continue;
                            }

                            #region Calculate Binding Flags
                            bool isPublic = fieldAccess == FieldAttributes.Public;
                            bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0;
                            BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
                            #endregion

                            RuntimeFieldInfo runtimeFieldInfo =
                            new MdFieldInfo(tkField, fieldAttributes, declaringType.GetTypeHandleInternal(), m_runtimeTypeCache, bindingFlags);

                            list.Add(runtimeFieldInfo);
                        }
                    }
                }

                private void AddSpecialInterface(ref ListBuilder<RuntimeType> list, Filter filter, RuntimeType iList, bool addSubInterface)
                {
                    if (iList.IsAssignableFrom(ReflectedType))
                    {
                        if (filter.Match(RuntimeTypeHandle.GetUtf8Name(iList)))
                            list.Add(iList);

                        if (addSubInterface)
                        {
                            Type[] iFaces = iList.GetInterfaces();
                            for (int j = 0; j < iFaces.Length; j++)
                            {
                                RuntimeType iFace = (RuntimeType)iFaces[j];
                                if (iFace.IsGenericType && filter.Match(RuntimeTypeHandle.GetUtf8Name(iFace)))
                                    list.Add(iFace);
                            }
                        }
                    }
                }

                private RuntimeType[] PopulateInterfaces(Filter filter)
                {
                    ListBuilder<RuntimeType> list = new ListBuilder<RuntimeType>();

                    RuntimeType declaringType = ReflectedType;

                    if (!RuntimeTypeHandle.IsGenericVariable(declaringType))
                    {
                        Type[] ifaces = RuntimeTypeHandle.GetInterfaces(declaringType);

                        if (ifaces != null)
                        {
                            for (int i = 0; i < ifaces.Length; i++)
                            {
                                RuntimeType interfaceType = (RuntimeType)ifaces[i];

                                if (filter.RequiresStringComparison())
                                {
                                    if (!filter.Match(RuntimeTypeHandle.GetUtf8Name(interfaceType)))
                                        continue;
                                }

                                Debug.Assert(interfaceType.IsInterface);
                                list.Add(interfaceType);
                            }
                        }

                        if (ReflectedType.IsSZArray)
                        {
                            RuntimeType arrayType = (RuntimeType)ReflectedType.GetElementType();

                            if (!arrayType.IsPointer)
                            {
                                AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IList<>).MakeGenericType(arrayType), true);

                                // To avoid adding a duplicate IEnumerable<T>, we don't add the sub interfaces of IReadOnlyList.
                                // Instead, we add IReadOnlyCollection<T> separately.
                                AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IReadOnlyList<>).MakeGenericType(arrayType), false);
                                AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IReadOnlyCollection<>).MakeGenericType(arrayType), false);
                            }
                        }
                    }
                    else
                    {
                        List<RuntimeType> al = new List<RuntimeType>();

                        // Get all constraints
                        Type[] constraints = declaringType.GetGenericParameterConstraints();

                        // Populate transitive closure of all interfaces in constraint set
                        for (int i = 0; i < constraints.Length; i++)
                        {
                            RuntimeType constraint = (RuntimeType)constraints[i];
                            if (constraint.IsInterface)
                                al.Add(constraint);

                            Type[] temp = constraint.GetInterfaces();
                            for (int j = 0; j < temp.Length; j++)
                                al.Add(temp[j] as RuntimeType);
                        }

                        // Remove duplicates
                        Dictionary<RuntimeType, RuntimeType> ht = new Dictionary<RuntimeType, RuntimeType>();
                        for (int i = 0; i < al.Count; i++)
                        {
                            RuntimeType constraint = al[i];
                            if (!ht.ContainsKey(constraint))
                                ht[constraint] = constraint;
                        }

                        RuntimeType[] interfaces = new RuntimeType[ht.Values.Count];
                        ht.Values.CopyTo(interfaces, 0);

                        // Populate link-list
                        for (int i = 0; i < interfaces.Length; i++)
                        {
                            if (filter.RequiresStringComparison())
                            {
                                if (!filter.Match(RuntimeTypeHandle.GetUtf8Name(interfaces[i])))
                                    continue;
                            }

                            list.Add(interfaces[i]);
                        }
                    }

                    return list.ToArray();
                }

                private unsafe RuntimeType[] PopulateNestedClasses(Filter filter)
                {
                    RuntimeType declaringType = ReflectedType;

                    while (RuntimeTypeHandle.IsGenericVariable(declaringType))
                    {
                        declaringType = declaringType.GetBaseType();
                    }

                    int tkEnclosingType = RuntimeTypeHandle.GetToken(declaringType);

                    // For example, TypeDescs do not have metadata tokens
                    if (MdToken.IsNullToken(tkEnclosingType))
                        return Array.Empty<RuntimeType>();

                    ListBuilder<RuntimeType> list = new ListBuilder<RuntimeType>();

                    RuntimeModule moduleHandle = RuntimeTypeHandle.GetModule(declaringType);
                    MetadataImport scope = ModuleHandle.GetMetadataImport(moduleHandle);

                    MetadataEnumResult tkNestedClasses;
                    scope.EnumNestedTypes(tkEnclosingType, out tkNestedClasses);

                    for (int i = 0; i < tkNestedClasses.Length; i++)
                    {
                        RuntimeType nestedType = null;

                        try
                        {
                            nestedType = ModuleHandle.ResolveTypeHandleInternal(moduleHandle, tkNestedClasses[i], null, null);
                        }
                        catch (System.TypeLoadException)
                        {
                            // In a reflection emit scenario, we may have a token for a class which 
                            // has not been baked and hence cannot be loaded. 
                            continue;
                        }

                        if (filter.RequiresStringComparison())
                        {
                            if (!filter.Match(RuntimeTypeHandle.GetUtf8Name(nestedType)))
                                continue;
                        }

                        list.Add(nestedType);
                    }

                    return list.ToArray();
                }

                private unsafe RuntimeEventInfo[] PopulateEvents(Filter filter)
                {
                    Contract.Requires(ReflectedType != null);

                    // Do not create the dictionary if we are filtering the properties by name already
                    Dictionary<String, RuntimeEventInfo> csEventInfos = filter.CaseSensitive() ? null :
                        new Dictionary<String, RuntimeEventInfo>();

                    RuntimeType declaringType = ReflectedType;
                    ListBuilder<RuntimeEventInfo> list = new ListBuilder<RuntimeEventInfo>();

                    if (!RuntimeTypeHandle.IsInterface(declaringType))
                    {
                        while (RuntimeTypeHandle.IsGenericVariable(declaringType))
                            declaringType = declaringType.GetBaseType();

                        // Populate associates off of the class hierarchy
                        while (declaringType != null)
                        {
                            PopulateEvents(filter, declaringType, csEventInfos, ref list);
                            declaringType = RuntimeTypeHandle.GetBaseType(declaringType);
                        }
                    }
                    else
                    {
                        // Populate associates for this interface 
                        PopulateEvents(filter, declaringType, csEventInfos, ref list);
                    }

                    return list.ToArray();
                }

                private unsafe void PopulateEvents(
                    Filter filter, RuntimeType declaringType, Dictionary<String, RuntimeEventInfo> csEventInfos, ref ListBuilder<RuntimeEventInfo> list)
                {
                    int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType);

                    // Arrays, Pointers, ByRef types and others generated only the fly by the RT do not have tokens.
                    if (MdToken.IsNullToken(tkDeclaringType))
                        return;

                    MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(declaringType);

                    MetadataEnumResult tkEvents;
                    scope.EnumEvents(tkDeclaringType, out tkEvents);

                    for (int i = 0; i < tkEvents.Length; i++)
                    {
                        int tkEvent = tkEvents[i];
                        bool isPrivate;

                        Debug.Assert(!MdToken.IsNullToken(tkEvent));
                        Debug.Assert(MdToken.IsTokenOfType(tkEvent, MetadataTokenType.Event));

                        if (filter.RequiresStringComparison())
                        {
                            Utf8String name;
                            name = scope.GetName(tkEvent);

                            if (!filter.Match(name))
                                continue;
                        }

                        RuntimeEventInfo eventInfo = new RuntimeEventInfo(
                            tkEvent, declaringType, m_runtimeTypeCache, out isPrivate);

                        #region Remove Inherited Privates
                        if (declaringType != m_runtimeTypeCache.GetRuntimeType() && isPrivate)
                            continue;
                        #endregion

                        #region Remove Duplicates
                        if (csEventInfos != null)
                        {
                            string name = eventInfo.Name;

                            if (csEventInfos.GetValueOrDefault(name) != null)
                                continue;

                            csEventInfos[name] = eventInfo;
                        }
                        else
                        {
                            if (list.Count > 0)
                                break;
                        }
                        #endregion

                        list.Add(eventInfo);
                    }
                }

                private unsafe RuntimePropertyInfo[] PopulateProperties(Filter filter)
                {
                    Contract.Requires(ReflectedType != null);

                    // m_csMemberInfos can be null at this point. It will be initialized when Insert
                    // is called in Populate after this returns.

                    RuntimeType declaringType = ReflectedType;
                    Debug.Assert(declaringType != null);

                    ListBuilder<RuntimePropertyInfo> list = new ListBuilder<RuntimePropertyInfo>();

                    if (!RuntimeTypeHandle.IsInterface(declaringType))
                    {
                        while (RuntimeTypeHandle.IsGenericVariable(declaringType))
                            declaringType = declaringType.GetBaseType();

                        // Do not create the dictionary if we are filtering the properties by name already
                        Dictionary<String, List<RuntimePropertyInfo>> csPropertyInfos = filter.CaseSensitive() ? null :
                            new Dictionary<String, List<RuntimePropertyInfo>>();

                        // All elements automatically initialized to false.
                        bool[] usedSlots = new bool[RuntimeTypeHandle.GetNumVirtuals(declaringType)];

                        // Populate associates off of the class hierarchy
                        do
                        {
                            PopulateProperties(filter, declaringType, csPropertyInfos, usedSlots, ref list);
                            declaringType = RuntimeTypeHandle.GetBaseType(declaringType);
                        } while (declaringType != null);
                    }
                    else
                    {
                        // Populate associates for this interface 
                        PopulateProperties(filter, declaringType, null, null, ref list);
                    }

                    return list.ToArray();
                }

                private unsafe void PopulateProperties(
                    Filter filter,
                    RuntimeType declaringType,
                    Dictionary<String, List<RuntimePropertyInfo>> csPropertyInfos,
                    bool[] usedSlots,
                    ref ListBuilder<RuntimePropertyInfo> list)
                {
                    int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType);

                    // Arrays, Pointers, ByRef types and others generated only the fly by the RT do not have tokens.
                    if (MdToken.IsNullToken(tkDeclaringType))
                        return;

                    MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(declaringType);

                    MetadataEnumResult tkProperties;
                    scope.EnumProperties(tkDeclaringType, out tkProperties);

                    RuntimeModule declaringModuleHandle = RuntimeTypeHandle.GetModule(declaringType);

                    int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType);

                    Debug.Assert((declaringType.IsInterface && usedSlots == null && csPropertyInfos == null) ||
                                    (!declaringType.IsInterface && usedSlots != null && usedSlots.Length >= numVirtuals));

                    for (int i = 0; i < tkProperties.Length; i++)
                    {
                        int tkProperty = tkProperties[i];
                        bool isPrivate;

                        Debug.Assert(!MdToken.IsNullToken(tkProperty));
                        Debug.Assert(MdToken.IsTokenOfType(tkProperty, MetadataTokenType.Property));

                        if (filter.RequiresStringComparison())
                        {
                            if (!ModuleHandle.ContainsPropertyMatchingHash(declaringModuleHandle, tkProperty, filter.GetHashToMatch()))
                            {
                                Debug.Assert(!filter.Match(declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty)));
                                continue;
                            }

                            Utf8String name;
                            name = declaringType.GetRuntimeModule().MetadataImport.GetName(tkProperty);

                            if (!filter.Match(name))
                                continue;
                        }

                        RuntimePropertyInfo propertyInfo =
                            new RuntimePropertyInfo(
                            tkProperty, declaringType, m_runtimeTypeCache, out isPrivate);

                        // If this is a class, not an interface
                        if (usedSlots != null)
                        {
                            #region Remove Privates
                            if (declaringType != ReflectedType && isPrivate)
                                continue;
                            #endregion

                            #region Duplicate check based on vtable slots

                            // The inheritance of properties are defined by the inheritance of their 
                            // getters and setters.
                            // A property on a base type is "overriden" by a property on a sub type
                            // if the getter/setter of the latter occupies the same vtable slot as 
                            // the getter/setter of the former.

                            MethodInfo associateMethod = propertyInfo.GetGetMethod();
                            if (associateMethod == null)
                            {
                                // We only need to examine the setter if a getter doesn't exist.
                                // It is not logical for the getter to be virtual but not the setter.
                                associateMethod = propertyInfo.GetSetMethod();
                            }

                            if (associateMethod != null)
                            {
                                int slot = RuntimeMethodHandle.GetSlot((RuntimeMethodInfo)associateMethod);

                                if (slot < numVirtuals)
                                {
                                    Debug.Assert(associateMethod.IsVirtual);
                                    if (usedSlots[slot] == true)
                                        continue;
                                    else
                                        usedSlots[slot] = true;
                                }
                            }
                            #endregion

                            #region Duplicate check based on name and signature

                            // For backward compatibility, even if the vtable slots don't match, we will still treat
                            // a property as duplicate if the names and signatures match.

                            if (csPropertyInfos != null)
                            {
                                string name = propertyInfo.Name;

                                List<RuntimePropertyInfo> cache = csPropertyInfos.GetValueOrDefault(name);

                                if (cache == null)
                                {
                                    cache = new List<RuntimePropertyInfo>(1);
                                    csPropertyInfos[name] = cache;
                                }

                                for (int j = 0; j < cache.Count; j++)
                                {
                                    if (propertyInfo.EqualsSig(cache[j]))
                                    {
                                        cache = null;
                                        break;
                                    }
                                }

                                if (cache == null)
                                    continue;

                                cache.Add(propertyInfo);
                            }
                            else
                            {
                                bool duplicate = false;

                                for (int j = 0; j < list.Count; j++)
                                {
                                    if (propertyInfo.EqualsSig(list[j]))
                                    {
                                        duplicate = true;
                                        break;
                                    }
                                }

                                if (duplicate)
                                    continue;
                            }
                            #endregion
                        }

                        list.Add(propertyInfo);
                    }
                }
                #endregion

                #region NonPrivate Members
                internal T[] GetMemberList(MemberListType listType, string name, CacheType cacheType)
                {
                    T[] list = null;

                    switch (listType)
                    {
                        case MemberListType.CaseSensitive:
                            list = m_csMemberInfos[name];
                            if (list != null)
                                return list;

                            return Populate(name, listType, cacheType);

                        case MemberListType.CaseInsensitive:
                            list = m_cisMemberInfos[name];
                            if (list != null)
                                return list;

                            return Populate(name, listType, cacheType);

                        default:
                            Debug.Assert(listType == MemberListType.All);
                            if (Volatile.Read(ref m_cacheComplete))
                                return m_allMembers;

                            return Populate(null, listType, cacheType);
                    }
                }

                internal RuntimeType ReflectedType
                {
                    get
                    {
                        return m_runtimeTypeCache.GetRuntimeType();
                    }
                }
                #endregion
            }
            #endregion

            #region Private Data Members
            private RuntimeType m_runtimeType;
            private RuntimeType m_enclosingType;
            private TypeCode m_typeCode;
            private string m_name;
            private string m_fullname;
            private string m_toString;
            private string m_namespace;
            private string m_serializationname;
            private bool m_isGlobal;
            private bool m_bIsDomainInitialized;
            private MemberInfoCache<RuntimeMethodInfo> m_methodInfoCache;
            private MemberInfoCache<RuntimeConstructorInfo> m_constructorInfoCache;
            private MemberInfoCache<RuntimeFieldInfo> m_fieldInfoCache;
            private MemberInfoCache<RuntimeType> m_interfaceCache;
            private MemberInfoCache<RuntimeType> m_nestedClassesCache;
            private MemberInfoCache<RuntimePropertyInfo> m_propertyInfoCache;
            private MemberInfoCache<RuntimeEventInfo> m_eventInfoCache;
            private static CerHashtable<RuntimeMethodInfo, RuntimeMethodInfo> s_methodInstantiations;
            private static Object s_methodInstantiationsLock;
            private string m_defaultMemberName;
            private Object m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values.
            #endregion

            #region Constructor
            internal RuntimeTypeCache(RuntimeType runtimeType)
            {
                m_typeCode = TypeCode.Empty;
                m_runtimeType = runtimeType;
                m_isGlobal = RuntimeTypeHandle.GetModule(runtimeType).RuntimeType == runtimeType;
            }
            #endregion

            #region Private Members
            private string ConstructName(ref string name, TypeNameFormatFlags formatFlags)
            {
                if (name == null)
                {
                    name = new RuntimeTypeHandle(m_runtimeType).ConstructName(formatFlags);
                }
                return name;
            }

            private T[] GetMemberList<T>(ref MemberInfoCache<T> m_cache, MemberListType listType, string name, CacheType cacheType)
                where T : MemberInfo
            {
                MemberInfoCache<T> existingCache = GetMemberCache<T>(ref m_cache);
                return existingCache.GetMemberList(listType, name, cacheType);
            }

            private MemberInfoCache<T> GetMemberCache<T>(ref MemberInfoCache<T> m_cache)
                where T : MemberInfo
            {
                MemberInfoCache<T> existingCache = m_cache;

                if (existingCache == null)
                {
                    MemberInfoCache<T> newCache = new MemberInfoCache<T>(this);
                    existingCache = Interlocked.CompareExchange(ref m_cache, newCache, null);
                    if (existingCache == null)
                        existingCache = newCache;
                }

                return existingCache;
            }
            #endregion

            #region Internal Members

            internal Object GenericCache
            {
                get { return m_genericCache; }
                set { m_genericCache = value; }
            }

            internal bool DomainInitialized
            {
                get { return m_bIsDomainInitialized; }
                set { m_bIsDomainInitialized = value; }
            }

            internal string GetName(TypeNameKind kind)
            {
                switch (kind)
                {
                    case TypeNameKind.Name:
                        // No namespace, full instantiation, and assembly.
                        return ConstructName(ref m_name, TypeNameFormatFlags.FormatBasic);

                    case TypeNameKind.FullName:
                        // We exclude the types that contain generic parameters because their names cannot be roundtripped.
                        // We allow generic type definitions (and their refs, ptrs, and arrays) because their names can be roundtriped.
                        // Theoretically generic types instantiated with generic type definitions can be roundtripped, e.g. List`1<Dictionary`2>.
                        // But these kind of types are useless, rare, and hard to identity. We would need to recursively examine all the 
                        // generic arguments with the same criteria. We will exclude them unless we see a real user scenario.
                        if (!m_runtimeType.GetRootElementType().IsGenericTypeDefinition && m_runtimeType.ContainsGenericParameters)
                            return null;

                        // No assembly.
                        return ConstructName(ref m_fullname, TypeNameFormatFlags.FormatNamespace | TypeNameFormatFlags.FormatFullInst);

                    case TypeNameKind.ToString:
                        // No full instantiation and assembly.
                        return ConstructName(ref m_toString, TypeNameFormatFlags.FormatNamespace);

                    case TypeNameKind.SerializationName:
                        // Use FormatGenericParam in serialization. Otherwise we won't be able 
                        // to distinguish between a generic parameter and a normal type with the same name.
                        // e.g. Foo<T>.Bar(T t), the parameter type T could be !1 or a real type named "T".
                        // Excluding the version number in the assembly name for VTS.
                        return ConstructName(ref m_serializationname, TypeNameFormatFlags.FormatSerialization);

                    default:
                        throw new InvalidOperationException();
                }
            }

            internal unsafe string GetNameSpace()
            {
                // @Optimization - Use ConstructName to populate m_namespace
                if (m_namespace == null)
                {
                    Type type = m_runtimeType;
                    type = type.GetRootElementType();

                    while (type.IsNested)
                        type = type.DeclaringType;

                    m_namespace = RuntimeTypeHandle.GetMetadataImport((RuntimeType)type).GetNamespace(type.MetadataToken).ToString();
                }

                return m_namespace;
            }

            internal TypeCode TypeCode
            {
                get { return m_typeCode; }
                set { m_typeCode = value; }
            }

            internal unsafe RuntimeType GetEnclosingType()
            {
                if (m_enclosingType == null)
                {
                    // Use void as a marker of null enclosing type
                    RuntimeType enclosingType = RuntimeTypeHandle.GetDeclaringType(GetRuntimeType());
                    Debug.Assert(enclosingType != typeof(void));
                    m_enclosingType = enclosingType ?? (RuntimeType)typeof(void);
                }

                return (m_enclosingType == typeof(void)) ? null : m_enclosingType;
            }

            internal RuntimeType GetRuntimeType()
            {
                return m_runtimeType;
            }

            internal bool IsGlobal
            {
                get { return m_isGlobal; }
            }

            internal void InvalidateCachedNestedType()
            {
                m_nestedClassesCache = null;
            }

            internal string GetDefaultMemberName()
            {
                if (m_defaultMemberName == null)
                {
                    CustomAttributeData attr = null;
                    Type DefaultMemberAttrType = typeof(DefaultMemberAttribute);
                    for (RuntimeType t = m_runtimeType; t != null; t = t.GetBaseType())
                    {
                        IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes(t);
                        for (int i = 0; i < attrs.Count; i++)
                        {
                            if (Object.ReferenceEquals(attrs[i].Constructor.DeclaringType, DefaultMemberAttrType))
                            {
                                attr = attrs[i];
                                break;
                            }
                        }

                        if (attr != null)
                        {
                            m_defaultMemberName = attr.ConstructorArguments[0].Value as string;
                            break;
                        }
                    }
                }

                return m_defaultMemberName;
            }
            #endregion

            #region Caches Accessors
            internal MethodInfo GetGenericMethodInfo(RuntimeMethodHandleInternal genericMethod)
            {
                LoaderAllocator la = RuntimeMethodHandle.GetLoaderAllocator(genericMethod);

                RuntimeMethodInfo rmi = new RuntimeMethodInfo(
                    genericMethod, RuntimeMethodHandle.GetDeclaringType(genericMethod), this,
                    RuntimeMethodHandle.GetAttributes(genericMethod), (BindingFlags)(-1), la);

                RuntimeMethodInfo crmi;
                if (la != null)
                {
                    crmi = la.m_methodInstantiations[rmi];
                }
                else
                {
                    crmi = s_methodInstantiations[rmi];
                }
                if (crmi != null)
                    return crmi;

                if (s_methodInstantiationsLock == null)
                    Interlocked.CompareExchange(ref s_methodInstantiationsLock, new Object(), null);

                bool lockTaken = false;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    Monitor.Enter(s_methodInstantiationsLock, ref lockTaken);

                    if (la != null)
                    {
                        crmi = la.m_methodInstantiations[rmi];
                        if (crmi != null)
                            return crmi;
                        la.m_methodInstantiations[rmi] = rmi;
                    }
                    else
                    {
                        crmi = s_methodInstantiations[rmi];
                        if (crmi != null)
                            return crmi;
                        s_methodInstantiations[rmi] = rmi;
                    }
                }
                finally
                {
                    if (lockTaken)
                    {
                        Monitor.Exit(s_methodInstantiationsLock);
                    }
                }

                return rmi;
            }

            internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string name)
            {
                return GetMemberList<RuntimeMethodInfo>(ref m_methodInfoCache, listType, name, CacheType.Method);
            }

            internal RuntimeConstructorInfo[] GetConstructorList(MemberListType listType, string name)
            {
                return GetMemberList<RuntimeConstructorInfo>(ref m_constructorInfoCache, listType, name, CacheType.Constructor);
            }

            internal RuntimePropertyInfo[] GetPropertyList(MemberListType listType, string name)
            {
                return GetMemberList<RuntimePropertyInfo>(ref m_propertyInfoCache, listType, name, CacheType.Property);
            }

            internal RuntimeEventInfo[] GetEventList(MemberListType listType, string name)
            {
                return GetMemberList<RuntimeEventInfo>(ref m_eventInfoCache, listType, name, CacheType.Event);
            }

            internal RuntimeFieldInfo[] GetFieldList(MemberListType listType, string name)
            {
                return GetMemberList<RuntimeFieldInfo>(ref m_fieldInfoCache, listType, name, CacheType.Field);
            }

            internal RuntimeType[] GetInterfaceList(MemberListType listType, string name)
            {
                return GetMemberList<RuntimeType>(ref m_interfaceCache, listType, name, CacheType.Interface);
            }

            internal RuntimeType[] GetNestedTypeList(MemberListType listType, string name)
            {
                return GetMemberList<RuntimeType>(ref m_nestedClassesCache, listType, name, CacheType.NestedType);
            }

            internal MethodBase GetMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method)
            {
                GetMemberCache<RuntimeMethodInfo>(ref m_methodInfoCache);
                return m_methodInfoCache.AddMethod(declaringType, method, CacheType.Method);
            }

            internal MethodBase GetConstructor(RuntimeType declaringType, RuntimeMethodHandleInternal constructor)
            {
                GetMemberCache<RuntimeConstructorInfo>(ref m_constructorInfoCache);
                return m_constructorInfoCache.AddMethod(declaringType, constructor, CacheType.Constructor);
            }

            internal FieldInfo GetField(RuntimeFieldHandleInternal field)
            {
                GetMemberCache<RuntimeFieldInfo>(ref m_fieldInfoCache);
                return m_fieldInfoCache.AddField(field);
            }

            #endregion
        }
        #endregion

        #region Static Members

        #region Internal
        internal static RuntimeType GetType(String typeName, bool throwOnError, bool ignoreCase, bool reflectionOnly,
            ref StackCrawlMark stackMark)
        {
            if (typeName == null)
                throw new ArgumentNullException(nameof(typeName));
            Contract.EndContractBlock();

            return RuntimeTypeHandle.GetTypeByName(
                typeName, throwOnError, ignoreCase, reflectionOnly, ref stackMark, false);
        }

        internal static MethodBase GetMethodBase(RuntimeModule scope, int typeMetadataToken)
        {
            return GetMethodBase(ModuleHandle.ResolveMethodHandleInternal(scope, typeMetadataToken));
        }

        internal static MethodBase GetMethodBase(IRuntimeMethodInfo methodHandle)
        {
            return GetMethodBase(null, methodHandle);
        }

        internal static MethodBase GetMethodBase(RuntimeType reflectedType, IRuntimeMethodInfo methodHandle)
        {
            MethodBase retval = RuntimeType.GetMethodBase(reflectedType, methodHandle.Value);
            GC.KeepAlive(methodHandle);
            return retval;
        }

        internal unsafe static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle)
        {
            Debug.Assert(!methodHandle.IsNullHandle());

            if (RuntimeMethodHandle.IsDynamicMethod(methodHandle))
            {
                Resolver resolver = RuntimeMethodHandle.GetResolver(methodHandle);

                if (resolver != null)
                    return resolver.GetDynamicMethod();

                return null;
            }

            // verify the type/method relationship
            RuntimeType declaredType = RuntimeMethodHandle.GetDeclaringType(methodHandle);

            RuntimeType[] methodInstantiation = null;

            if (reflectedType == null)
                reflectedType = declaredType as RuntimeType;

            if (reflectedType != declaredType && !reflectedType.IsSubclassOf(declaredType))
            {
                // object[] is assignable from string[].
                if (reflectedType.IsArray)
                {
                    // The whole purpose of this chunk of code is not only for error checking.
                    // GetMember has a side effect of populating the member cache of reflectedType,
                    // doing so will ensure we construct the correct MethodInfo/ConstructorInfo objects.
                    // Without this the reflectedType.Cache.GetMethod call below may return a MethodInfo
                    // object whose ReflectedType is string[] and DeclaringType is object[]. That would
                    // be (arguabally) incorrect because string[] is not a subclass of object[].
                    MethodBase[] methodBases = reflectedType.GetMember(
                        RuntimeMethodHandle.GetName(methodHandle), MemberTypes.Constructor | MemberTypes.Method,
                        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) as MethodBase[];

                    bool loaderAssuredCompatible = false;
                    for (int i = 0; i < methodBases.Length; i++)
                    {
                        IRuntimeMethodInfo rmi = (IRuntimeMethodInfo)methodBases[i];
                        if (rmi.Value.Value == methodHandle.Value)
                            loaderAssuredCompatible = true;
                    }

                    if (!loaderAssuredCompatible)
                        throw new ArgumentException(String.Format(
                            CultureInfo.CurrentCulture, SR.Argument_ResolveMethodHandle,
                            reflectedType.ToString(), declaredType.ToString()));
                }
                // Action<in string> is assignable from, but not a subclass of Action<in object>.
                else if (declaredType.IsGenericType)
                {
                    // ignoring instantiation is the ReflectedType a subtype of the DeclaringType
                    RuntimeType declaringDefinition = (RuntimeType)declaredType.GetGenericTypeDefinition();

                    RuntimeType baseType = reflectedType;

                    while (baseType != null)
                    {
                        RuntimeType baseDefinition = baseType;

                        if (baseDefinition.IsGenericType && !baseType.IsGenericTypeDefinition)
                            baseDefinition = (RuntimeType)baseDefinition.GetGenericTypeDefinition();

                        if (baseDefinition == declaringDefinition)
                            break;

                        baseType = baseType.GetBaseType();
                    }

                    if (baseType == null)
                    {
                        // ignoring instantiation is the ReflectedType is not a subtype of the DeclaringType
                        throw new ArgumentException(String.Format(
                            CultureInfo.CurrentCulture, SR.Argument_ResolveMethodHandle,
                            reflectedType.ToString(), declaredType.ToString()));
                    }

                    // remap the method to same method on the subclass ReflectedType
                    declaredType = baseType;

                    // if the original methodHandle was the definition then we don't need to rebind generic method arguments
                    // because all RuntimeMethodHandles retrieved off of the canonical method table are definitions. That's 
                    // why for everything else we need to rebind the generic method arguments. 
                    if (!RuntimeMethodHandle.IsGenericMethodDefinition(methodHandle))
                    {
                        methodInstantiation = RuntimeMethodHandle.GetMethodInstantiationInternal(methodHandle);
                    }

                    // lookup via v-table slot the RuntimeMethodHandle on the new declaring type
                    methodHandle = RuntimeMethodHandle.GetMethodFromCanonical(methodHandle, declaredType);
                }
                else if (!declaredType.IsAssignableFrom(reflectedType))
                {
                    // declaredType is not Array, not generic, and not assignable from reflectedType
                    throw new ArgumentException(String.Format(
                        CultureInfo.CurrentCulture, SR.Argument_ResolveMethodHandle,
                        reflectedType.ToString(), declaredType.ToString()));
                }
            }

            // If methodInstantiation is not null, GetStubIfNeeded will rebind the generic method arguments
            // if declaredType is an instantiated generic type and methodHandle is not generic, get the instantiated MethodDesc (if needed)
            // if declaredType is a value type, get the unboxing stub (if needed)

            // this is so that our behavior here is consistent with that of Type.GetMethod
            // See MemberInfoCache<RuntimeConstructorInfo>.PopulateMethods and MemberInfoCache<RuntimeMethodInfoInfo>.PopulateConstructors

            methodHandle = RuntimeMethodHandle.GetStubIfNeeded(methodHandle, declaredType, methodInstantiation);
            MethodBase retval;

            if (RuntimeMethodHandle.IsConstructor(methodHandle))
            {
                // Constructor case: constructors cannot be generic
                retval = reflectedType.Cache.GetConstructor(declaredType, methodHandle);
            }
            else
            {
                // Method case
                if (RuntimeMethodHandle.HasMethodInstantiation(methodHandle) && !RuntimeMethodHandle.IsGenericMethodDefinition(methodHandle))
                    retval = reflectedType.Cache.GetGenericMethodInfo(methodHandle);
                else
                    retval = reflectedType.Cache.GetMethod(declaredType, methodHandle);
            }

            GC.KeepAlive(methodInstantiation);
            return retval;
        }

        internal Object GenericCache
        {
            get { return Cache.GenericCache; }
            set { Cache.GenericCache = value; }
        }

        internal bool DomainInitialized
        {
            get { return Cache.DomainInitialized; }
            set { Cache.DomainInitialized = value; }
        }

        internal unsafe static FieldInfo GetFieldInfo(IRuntimeFieldInfo fieldHandle)
        {
            return GetFieldInfo(RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle), fieldHandle);
        }

        internal unsafe static FieldInfo GetFieldInfo(RuntimeType reflectedType, IRuntimeFieldInfo field)
        {
            RuntimeFieldHandleInternal fieldHandle = field.Value;

            // verify the type/method relationship
            if (reflectedType == null)
            {
                reflectedType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle);
            }
            else
            {
                RuntimeType declaredType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle);
                if (reflectedType != declaredType)
                {
                    if (!RuntimeFieldHandle.AcquiresContextFromThis(fieldHandle) ||
                        !RuntimeTypeHandle.CompareCanonicalHandles(declaredType, reflectedType))
                    {
                        throw new ArgumentException(String.Format(
                            CultureInfo.CurrentCulture, SR.Argument_ResolveFieldHandle,
                            reflectedType.ToString(),
                            declaredType.ToString()));
                    }
                }
            }

            FieldInfo retVal = reflectedType.Cache.GetField(fieldHandle);
            GC.KeepAlive(field);
            return retVal;
        }

        // Called internally
        private unsafe static PropertyInfo GetPropertyInfo(RuntimeType reflectedType, int tkProperty)
        {
            RuntimePropertyInfo property = null;
            RuntimePropertyInfo[] candidates =
                reflectedType.Cache.GetPropertyList(MemberListType.All, null);

            for (int i = 0; i < candidates.Length; i++)
            {
                property = candidates[i];
                if (property.MetadataToken == tkProperty)
                    return property;
            }

            Contract.Assume(false, "Unreachable code");
            throw new SystemException();
        }

        private static void ThrowIfTypeNeverValidGenericArgument(RuntimeType type)
        {
            if (type.IsPointer || type.IsByRef || type == typeof(void))
                throw new ArgumentException(
                    SR.Format(SR.Argument_NeverValidGenericArgument, type.ToString()));
        }


        internal static void SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParamters)
        {
            if (genericArguments == null)
                throw new ArgumentNullException();
            Contract.EndContractBlock();

            for (int i = 0; i < genericArguments.Length; i++)
            {
                if (genericArguments[i] == null)
                    throw new ArgumentNullException();

                ThrowIfTypeNeverValidGenericArgument(genericArguments[i]);
            }

            if (genericArguments.Length != genericParamters.Length)
                throw new ArgumentException(
                    SR.Format(SR.Argument_NotEnoughGenArguments, genericArguments.Length, genericParamters.Length));
        }

        internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
        {
            RuntimeType[] typeContext = null;
            RuntimeType[] methodContext = null;
            RuntimeType[] genericParamters = null;

            if (definition is Type)
            {
                RuntimeType genericTypeDefinition = (RuntimeType)definition;
                genericParamters = genericTypeDefinition.GetGenericArgumentsInternal();
                typeContext = genericArguments;
            }
            else
            {
                RuntimeMethodInfo genericMethodDefinition = (RuntimeMethodInfo)definition;
                genericParamters = genericMethodDefinition.GetGenericArgumentsInternal();
                methodContext = genericArguments;

                RuntimeType declaringType = (RuntimeType)genericMethodDefinition.DeclaringType;
                if (declaringType != null)
                {
                    typeContext = declaringType.GetTypeHandleInternal().GetInstantiationInternal();
                }
            }

            for (int i = 0; i < genericArguments.Length; i++)
            {
                Type genericArgument = genericArguments[i];
                Type genericParameter = genericParamters[i];

                if (!RuntimeTypeHandle.SatisfiesConstraints(genericParameter.GetTypeHandleInternal().GetTypeChecked(),
                    typeContext, methodContext, genericArgument.GetTypeHandleInternal().GetTypeChecked()))
                {
                    throw new ArgumentException(
                        SR.Format(SR.Argument_GenConstraintViolation, i.ToString(CultureInfo.CurrentCulture), genericArgument.ToString(), definition.ToString(), genericParameter.ToString()), e);
                }
            }
        }

        private static void SplitName(string fullname, out string name, out string ns)
        {
            name = null;
            ns = null;

            if (fullname == null)
                return;

            // Get namespace
            int nsDelimiter = fullname.LastIndexOf(".", StringComparison.Ordinal);
            if (nsDelimiter != -1)
            {
                ns = fullname.Substring(0, nsDelimiter);
                int nameLength = fullname.Length - ns.Length - 1;
                if (nameLength != 0)
                    name = fullname.Substring(nsDelimiter + 1, nameLength);
                else
                    name = "";
                Debug.Assert(fullname.Equals(ns + "." + name));
            }
            else
            {
                name = fullname;
            }
        }
        #endregion

        #region Filters
        internal static BindingFlags FilterPreCalculate(bool isPublic, bool isInherited, bool isStatic)
        {
            BindingFlags bindingFlags = isPublic ? BindingFlags.Public : BindingFlags.NonPublic;

            if (isInherited)
            {
                // We arrange things so the DeclaredOnly flag means "include inherited members"
                bindingFlags |= BindingFlags.DeclaredOnly;

                if (isStatic)
                {
                    bindingFlags |= BindingFlags.Static | BindingFlags.FlattenHierarchy;
                }
                else
                {
                    bindingFlags |= BindingFlags.Instance;
                }
            }
            else
            {
                if (isStatic)
                {
                    bindingFlags |= BindingFlags.Static;
                }
                else
                {
                    bindingFlags |= BindingFlags.Instance;
                }
            }

            return bindingFlags;
        }

        // Calculate prefixLookup, ignoreCase, and listType for use by GetXXXCandidates
        private static void FilterHelper(
            BindingFlags bindingFlags, ref string name, bool allowPrefixLookup, out bool prefixLookup,
            out bool ignoreCase, out MemberListType listType)
        {
            prefixLookup = false;
            ignoreCase = false;

            if (name != null)
            {
                if ((bindingFlags & BindingFlags.IgnoreCase) != 0)
                {
                    name = name.ToLower(CultureInfo.InvariantCulture);
                    ignoreCase = true;
                    listType = MemberListType.CaseInsensitive;
                }
                else
                {
                    listType = MemberListType.CaseSensitive;
                }

                if (allowPrefixLookup && name.EndsWith("*", StringComparison.Ordinal))
                {
                    // We set prefixLookup to true if name ends with a "*".
                    // We will also set listType to All so that all members are included in 
                    // the candidates which are later filtered by FilterApplyPrefixLookup.
                    name = name.Substring(0, name.Length - 1);
                    prefixLookup = true;
                    listType = MemberListType.All;
                }
            }
            else
            {
                listType = MemberListType.All;
            }
        }

        // Used by the singular GetXXX APIs (Event, Field, Interface, NestedType) where prefixLookup is not supported.
        private static void FilterHelper(BindingFlags bindingFlags, ref string name, out bool ignoreCase, out MemberListType listType)
        {
            bool prefixLookup;
            FilterHelper(bindingFlags, ref name, false, out prefixLookup, out ignoreCase, out listType);
        }

        // Only called by GetXXXCandidates, GetInterfaces, and GetNestedTypes when FilterHelper has set "prefixLookup" to true.
        // Most of the plural GetXXX methods allow prefix lookups while the singular GetXXX methods mostly do not.
        private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string name, bool ignoreCase)
        {
            Debug.Assert(name != null);

            if (ignoreCase)
            {
                if (!memberInfo.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase))
                    return false;
            }
            else
            {
                if (!memberInfo.Name.StartsWith(name, StringComparison.Ordinal))
                    return false;
            }

            return true;
        }


        // Used by FilterApplyType to perform all the filtering based on name and BindingFlags
        private static bool FilterApplyBase(
            MemberInfo memberInfo, BindingFlags bindingFlags, bool isPublic, bool isNonProtectedInternal, bool isStatic,
            string name, bool prefixLookup)
        {
            #region Preconditions
            Contract.Requires(memberInfo != null);
            Contract.Requires(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name)));
            #endregion

            #region Filter by Public & Private
            if (isPublic)
            {
                if ((bindingFlags & BindingFlags.Public) == 0)
                    return false;
            }
            else
            {
                if ((bindingFlags & BindingFlags.NonPublic) == 0)
                    return false;
            }
            #endregion

            bool isInherited = !Object.ReferenceEquals(memberInfo.DeclaringType, memberInfo.ReflectedType);

            #region Filter by DeclaredOnly
            if ((bindingFlags & BindingFlags.DeclaredOnly) != 0 && isInherited)
                return false;
            #endregion

            #region Filter by Static & Instance
            if (memberInfo.MemberType != MemberTypes.TypeInfo &&
                memberInfo.MemberType != MemberTypes.NestedType)
            {
                if (isStatic)
                {
                    if ((bindingFlags & BindingFlags.FlattenHierarchy) == 0 && isInherited)
                        return false;

                    if ((bindingFlags & BindingFlags.Static) == 0)
                        return false;
                }
                else
                {
                    if ((bindingFlags & BindingFlags.Instance) == 0)
                        return false;
                }
            }
            #endregion

            #region Filter by name wrt prefixLookup and implicitly by case sensitivity
            if (prefixLookup == true)
            {
                if (!FilterApplyPrefixLookup(memberInfo, name, (bindingFlags & BindingFlags.IgnoreCase) != 0))
                    return false;
            }
            #endregion

            #region Asymmetries
            // @Asymmetry - Internal, inherited, instance, non-protected, non-virtual, non-abstract members returned 
            //              iff BindingFlags !DeclaredOnly, Instance and Public are present except for fields
            if (((bindingFlags & BindingFlags.DeclaredOnly) == 0) &&        // DeclaredOnly not present
                 isInherited &&                                            // Is inherited Member

                (isNonProtectedInternal) &&                                 // Is non-protected internal member
                ((bindingFlags & BindingFlags.NonPublic) != 0) &&           // BindingFlag.NonPublic present 

                (!isStatic) &&                                              // Is instance member
                ((bindingFlags & BindingFlags.Instance) != 0))              // BindingFlag.Instance present 
            {
                MethodInfo methodInfo = memberInfo as MethodInfo;

                if (methodInfo == null)
                    return false;

                if (!methodInfo.IsVirtual && !methodInfo.IsAbstract)
                    return false;
            }
            #endregion

            return true;
        }


        // Used by GetInterface and GetNestedType(s) which don't need parameter type filtering.
        private static bool FilterApplyType(
            Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns)
        {
            Contract.Requires((object)type != null);
            Debug.Assert(type is RuntimeType);

            bool isPublic = type.IsNestedPublic || type.IsPublic;
            bool isStatic = false;

            if (!RuntimeType.FilterApplyBase(type, bindingFlags, isPublic, type.IsNestedAssembly, isStatic, name, prefixLookup))
                return false;

            if (ns != null && !type.Namespace.Equals(ns))
                return false;

            return true;
        }


        private static bool FilterApplyMethodInfo(
            RuntimeMethodInfo method, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes)
        {
            // Optimization: Pre-Calculate the method binding flags to avoid casting.
            return FilterApplyMethodBase(method, method.BindingFlags, bindingFlags, callConv, argumentTypes);
        }

        private static bool FilterApplyConstructorInfo(
            RuntimeConstructorInfo constructor, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes)
        {
            // Optimization: Pre-Calculate the method binding flags to avoid casting.
            return FilterApplyMethodBase(constructor, constructor.BindingFlags, bindingFlags, callConv, argumentTypes);
        }

        // Used by GetMethodCandidates/GetConstructorCandidates, InvokeMember, and CreateInstanceImpl to perform the necessary filtering.
        // Should only be called by FilterApplyMethodInfo and FilterApplyConstructorInfo.
        private static bool FilterApplyMethodBase(
            MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes)
        {
            Contract.Requires(methodBase != null);

            bindingFlags ^= BindingFlags.DeclaredOnly;

            #region Apply Base Filter
            if ((bindingFlags & methodFlags) != methodFlags)
                return false;
            #endregion

            #region Check CallingConvention
            if ((callConv & CallingConventions.Any) == 0)
            {
                if ((callConv & CallingConventions.VarArgs) != 0 &&
                    (methodBase.CallingConvention & CallingConventions.VarArgs) == 0)
                    return false;

                if ((callConv & CallingConventions.Standard) != 0 &&
                    (methodBase.CallingConvention & CallingConventions.Standard) == 0)
                    return false;
            }
            #endregion

            #region If argumentTypes supplied
            if (argumentTypes != null)
            {
                ParameterInfo[] parameterInfos = methodBase.GetParametersNoCopy();

                if (argumentTypes.Length != parameterInfos.Length)
                {
                    #region Invoke Member, Get\Set & Create Instance specific case
                    // If the number of supplied arguments differs than the number in the signature AND
                    // we are not filtering for a dynamic call -- InvokeMethod or CreateInstance -- filter out the method.
                    if ((bindingFlags &
                        (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetProperty | BindingFlags.SetProperty)) == 0)
                        return false;

                    bool testForParamArray = false;
                    bool excessSuppliedArguments = argumentTypes.Length > parameterInfos.Length;

                    if (excessSuppliedArguments)
                    { // more supplied arguments than parameters, additional arguments could be vararg
                        #region Varargs
                        // If method is not vararg, additional arguments can not be passed as vararg
                        if ((methodBase.CallingConvention & CallingConventions.VarArgs) == 0)
                        {
                            testForParamArray = true;
                        }
                        else
                        {
                            // If Binding flags did not include varargs we would have filtered this vararg method.
                            // This Invariant established during callConv check.
                            Debug.Assert((callConv & CallingConventions.VarArgs) != 0);
                        }
                        #endregion
                    }
                    else
                    {// fewer supplied arguments than parameters, missing arguments could be optional
                        #region OptionalParamBinding
                        if ((bindingFlags & BindingFlags.OptionalParamBinding) == 0)
                        {
                            testForParamArray = true;
                        }
                        else
                        {
                            // From our existing code, our policy here is that if a parameterInfo 
                            // is optional then all subsequent parameterInfos shall be optional. 

                            // Thus, iff the first parameterInfo is not optional then this MethodInfo is no longer a canidate.
                            if (!parameterInfos[argumentTypes.Length].IsOptional)
                                testForParamArray = true;
                        }
                        #endregion
                    }

                    #region ParamArray
                    if (testForParamArray)
                    {
                        if (parameterInfos.Length == 0)
                            return false;

                        // The last argument of the signature could be a param array. 
                        bool shortByMoreThanOneSuppliedArgument = argumentTypes.Length < parameterInfos.Length - 1;

                        if (shortByMoreThanOneSuppliedArgument)
                            return false;

                        ParameterInfo lastParameter = parameterInfos[parameterInfos.Length - 1];

                        if (!lastParameter.ParameterType.IsArray)
                            return false;

                        if (!lastParameter.IsDefined(typeof(ParamArrayAttribute), false))
                            return false;
                    }
                    #endregion

                    #endregion
                }
                else
                {
                    #region Exact Binding
                    if ((bindingFlags & BindingFlags.ExactBinding) != 0)
                    {
                        // Legacy behavior is to ignore ExactBinding when InvokeMember is specified.
                        // Why filter by InvokeMember? If the answer is we leave this to the binder then why not leave
                        // all the rest of this  to the binder too? Further, what other semanitc would the binder
                        // use for BindingFlags.ExactBinding besides this one? Further, why not include CreateInstance 
                        // in this if statement? That's just InvokeMethod with a constructor, right?
                        if ((bindingFlags & (BindingFlags.InvokeMethod)) == 0)
                        {
                            for (int i = 0; i < parameterInfos.Length; i++)
                            {
                                // a null argument type implies a null arg which is always a perfect match
                                if ((object)argumentTypes[i] != null && !Object.ReferenceEquals(parameterInfos[i].ParameterType, argumentTypes[i]))
                                    return false;
                            }
                        }
                    }
                    #endregion
                }
            }
            #endregion

            return true;
        }

        #endregion

        #endregion

        #region Private Data Members
        private object m_keepalive; // This will be filled with a LoaderAllocator reference when this RuntimeType represents a collectible type
        private IntPtr m_cache;
        internal IntPtr m_handle;

        internal static readonly RuntimeType ValueType = (RuntimeType)typeof(System.ValueType);
        internal static readonly RuntimeType EnumType = (RuntimeType)typeof(System.Enum);

        private static readonly RuntimeType ObjectType = (RuntimeType)typeof(System.Object);
        private static readonly RuntimeType StringType = (RuntimeType)typeof(System.String);
        private static readonly RuntimeType DelegateType = (RuntimeType)typeof(System.Delegate);
        #endregion

        #region Constructor
        internal RuntimeType() { throw new NotSupportedException(); }
        #endregion

        #region Private\Internal Members
        internal override bool CacheEquals(object o)
        {
            RuntimeType m = o as RuntimeType;

            if (m == null)
                return false;

            return m.m_handle.Equals(m_handle);
        }

        private RuntimeTypeCache Cache
        {
            get
            {
                if (m_cache.IsNull())
                {
                    IntPtr newgcHandle = new RuntimeTypeHandle(this).GetGCHandle(GCHandleType.WeakTrackResurrection);
                    IntPtr gcHandle = Interlocked.CompareExchange(ref m_cache, newgcHandle, (IntPtr)0);
                    // Leak the handle if the type is collectible. It will be reclaimed when
                    // the type goes away.
                    if (!gcHandle.IsNull() && !IsCollectible())
                        GCHandle.InternalFree(newgcHandle);
                }

                RuntimeTypeCache cache = GCHandle.InternalGet(m_cache) as RuntimeTypeCache;
                if (cache == null)
                {
                    cache = new RuntimeTypeCache(this);
                    RuntimeTypeCache existingCache = GCHandle.InternalCompareExchange(m_cache, cache, null, false) as RuntimeTypeCache;
                    if (existingCache != null)
                        cache = existingCache;
                }

                Debug.Assert(cache != null);
                return cache;
            }
        }

        private string GetDefaultMemberName()
        {
            return Cache.GetDefaultMemberName();
        }
        #endregion

        #region Type Overrides

        #region Get XXXInfo Candidates
        private ListBuilder<MethodInfo> GetMethodCandidates(
            String name, BindingFlags bindingAttr, CallingConventions callConv,
            Type[] types, bool allowPrefixLookup)
        {
            bool prefixLookup, ignoreCase;
            MemberListType listType;
            RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);

            RuntimeMethodInfo[] cache = Cache.GetMethodList(listType, name);

            ListBuilder<MethodInfo> candidates = new ListBuilder<MethodInfo>(cache.Length);
            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeMethodInfo methodInfo = cache[i];
                if (FilterApplyMethodInfo(methodInfo, bindingAttr, callConv, types) &&
                    (!prefixLookup || RuntimeType.FilterApplyPrefixLookup(methodInfo, name, ignoreCase)))
                {
                    candidates.Add(methodInfo);
                }
            }

            return candidates;
        }

        private ListBuilder<ConstructorInfo> GetConstructorCandidates(
            string name, BindingFlags bindingAttr, CallingConventions callConv,
            Type[] types, bool allowPrefixLookup)
        {
            bool prefixLookup, ignoreCase;
            MemberListType listType;
            RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);

            RuntimeConstructorInfo[] cache = Cache.GetConstructorList(listType, name);

            ListBuilder<ConstructorInfo> candidates = new ListBuilder<ConstructorInfo>(cache.Length);
            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeConstructorInfo constructorInfo = cache[i];
                if (FilterApplyConstructorInfo(constructorInfo, bindingAttr, callConv, types) &&
                    (!prefixLookup || RuntimeType.FilterApplyPrefixLookup(constructorInfo, name, ignoreCase)))
                {
                    candidates.Add(constructorInfo);
                }
            }

            return candidates;
        }


        private ListBuilder<PropertyInfo> GetPropertyCandidates(
            String name, BindingFlags bindingAttr, Type[] types, bool allowPrefixLookup)
        {
            bool prefixLookup, ignoreCase;
            MemberListType listType;
            RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);

            RuntimePropertyInfo[] cache = Cache.GetPropertyList(listType, name);

            bindingAttr ^= BindingFlags.DeclaredOnly;

            ListBuilder<PropertyInfo> candidates = new ListBuilder<PropertyInfo>(cache.Length);
            for (int i = 0; i < cache.Length; i++)
            {
                RuntimePropertyInfo propertyInfo = cache[i];
                if ((bindingAttr & propertyInfo.BindingFlags) == propertyInfo.BindingFlags &&
                    (!prefixLookup || RuntimeType.FilterApplyPrefixLookup(propertyInfo, name, ignoreCase)) &&
                    (types == null || (propertyInfo.GetIndexParameters().Length == types.Length)))
                {
                    candidates.Add(propertyInfo);
                }
            }

            return candidates;
        }

        private ListBuilder<EventInfo> GetEventCandidates(String name, BindingFlags bindingAttr, bool allowPrefixLookup)
        {
            bool prefixLookup, ignoreCase;
            MemberListType listType;
            RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);

            RuntimeEventInfo[] cache = Cache.GetEventList(listType, name);

            bindingAttr ^= BindingFlags.DeclaredOnly;

            ListBuilder<EventInfo> candidates = new ListBuilder<EventInfo>(cache.Length);
            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeEventInfo eventInfo = cache[i];
                if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags &&
                    (!prefixLookup || RuntimeType.FilterApplyPrefixLookup(eventInfo, name, ignoreCase)))
                {
                    candidates.Add(eventInfo);
                }
            }

            return candidates;
        }

        private ListBuilder<FieldInfo> GetFieldCandidates(String name, BindingFlags bindingAttr, bool allowPrefixLookup)
        {
            bool prefixLookup, ignoreCase;
            MemberListType listType;
            RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);

            RuntimeFieldInfo[] cache = Cache.GetFieldList(listType, name);

            bindingAttr ^= BindingFlags.DeclaredOnly;

            ListBuilder<FieldInfo> candidates = new ListBuilder<FieldInfo>(cache.Length);
            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeFieldInfo fieldInfo = cache[i];
                if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags &&
                    (!prefixLookup || FilterApplyPrefixLookup(fieldInfo, name, ignoreCase)))
                {
                    candidates.Add(fieldInfo);
                }
            }

            return candidates;
        }

        private ListBuilder<Type> GetNestedTypeCandidates(String fullname, BindingFlags bindingAttr, bool allowPrefixLookup)
        {
            bool prefixLookup, ignoreCase;
            bindingAttr &= ~BindingFlags.Static;
            string name, ns;
            MemberListType listType;
            SplitName(fullname, out name, out ns);
            RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);

            RuntimeType[] cache = Cache.GetNestedTypeList(listType, name);

            ListBuilder<Type> candidates = new ListBuilder<Type>(cache.Length);
            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeType nestedClass = cache[i];
                if (RuntimeType.FilterApplyType(nestedClass, bindingAttr, name, prefixLookup, ns))
                {
                    candidates.Add(nestedClass);
                }
            }

            return candidates;
        }
        #endregion

        #region Get All XXXInfos
        public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
        {
            return GetMethodCandidates(null, bindingAttr, CallingConventions.Any, null, false).ToArray();
        }

        public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
        {
            return GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, false).ToArray();
        }

        public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
        {
            return GetPropertyCandidates(null, bindingAttr, null, false).ToArray();
        }

        public override EventInfo[] GetEvents(BindingFlags bindingAttr)
        {
            return GetEventCandidates(null, bindingAttr, false).ToArray();
        }

        public override FieldInfo[] GetFields(BindingFlags bindingAttr)
        {
            return GetFieldCandidates(null, bindingAttr, false).ToArray();
        }

        public override Type[] GetInterfaces()
        {
            RuntimeType[] candidates = this.Cache.GetInterfaceList(MemberListType.All, null);
            Type[] interfaces = new Type[candidates.Length];
            for (int i = 0; i < candidates.Length; i++)
                JitHelpers.UnsafeSetArrayElement(interfaces, i, candidates[i]);

            return interfaces;
        }

        public override Type[] GetNestedTypes(BindingFlags bindingAttr)
        {
            return GetNestedTypeCandidates(null, bindingAttr, false).ToArray();
        }

        public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
        {
            ListBuilder<MethodInfo> methods = GetMethodCandidates(null, bindingAttr, CallingConventions.Any, null, false);
            ListBuilder<ConstructorInfo> constructors = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, false);
            ListBuilder<PropertyInfo> properties = GetPropertyCandidates(null, bindingAttr, null, false);
            ListBuilder<EventInfo> events = GetEventCandidates(null, bindingAttr, false);
            ListBuilder<FieldInfo> fields = GetFieldCandidates(null, bindingAttr, false);
            ListBuilder<Type> nestedTypes = GetNestedTypeCandidates(null, bindingAttr, false);
            // Interfaces are excluded from the result of GetMembers

            MemberInfo[] members = new MemberInfo[
                methods.Count +
                constructors.Count +
                properties.Count +
                events.Count +
                fields.Count +
                nestedTypes.Count];

            int i = 0;
            methods.CopyTo(members, i); i += methods.Count;
            constructors.CopyTo(members, i); i += constructors.Count;
            properties.CopyTo(members, i); i += properties.Count;
            events.CopyTo(members, i); i += events.Count;
            fields.CopyTo(members, i); i += fields.Count;
            nestedTypes.CopyTo(members, i); i += nestedTypes.Count;
            Debug.Assert(i == members.Length);

            return members;
        }

        public override InterfaceMapping GetInterfaceMap(Type ifaceType)
        {
            if (IsGenericParameter)
                throw new InvalidOperationException(SR.Arg_GenericParameter);

            if ((object)ifaceType == null)
                throw new ArgumentNullException(nameof(ifaceType));
            Contract.EndContractBlock();

            RuntimeType ifaceRtType = ifaceType as RuntimeType;

            if (ifaceRtType == null)
                throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(ifaceType));

            RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal();

            GetTypeHandleInternal().VerifyInterfaceIsImplemented(ifaceRtTypeHandle);
            Debug.Assert(ifaceType.IsInterface);  // VerifyInterfaceIsImplemented enforces this invariant
            Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant

            // SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with
            // SZArrayHelper and some runtime magic. We don't have accurate interface maps for them.
            if (IsSZArray && ifaceType.IsGenericType)
                throw new ArgumentException(SR.Argument_ArrayGetInterfaceMap);

            int ifaceInstanceMethodCount = RuntimeTypeHandle.GetNumVirtuals(ifaceRtType);

            InterfaceMapping im;
            im.InterfaceType = ifaceType;
            im.TargetType = this;
            im.InterfaceMethods = new MethodInfo[ifaceInstanceMethodCount];
            im.TargetMethods = new MethodInfo[ifaceInstanceMethodCount];

            for (int i = 0; i < ifaceInstanceMethodCount; i++)
            {
                RuntimeMethodHandleInternal ifaceRtMethodHandle = RuntimeTypeHandle.GetMethodAt(ifaceRtType, i);

                // GetMethodBase will convert this to the instantiating/unboxing stub if necessary
                MethodBase ifaceMethodBase = RuntimeType.GetMethodBase(ifaceRtType, ifaceRtMethodHandle);
                Debug.Assert(ifaceMethodBase is RuntimeMethodInfo);
                im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase;

                // If the slot is -1, then virtual stub dispatch is active.
                int slot = GetTypeHandleInternal().GetInterfaceMethodImplementationSlot(ifaceRtTypeHandle, ifaceRtMethodHandle);

                if (slot == -1) continue;

                RuntimeMethodHandleInternal classRtMethodHandle = RuntimeTypeHandle.GetMethodAt(this, slot);

                // GetMethodBase will convert this to the instantiating/unboxing stub if necessary
                MethodBase rtTypeMethodBase = RuntimeType.GetMethodBase(this, classRtMethodHandle);
                // a class may not implement all the methods of an interface (abstract class) so null is a valid value 
                Debug.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
                im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase;
            }

            return im;
        }
        #endregion

        #region Find XXXInfo
        protected override MethodInfo GetMethodImpl(
            String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
            Type[] types, ParameterModifier[] modifiers)
        {
            ListBuilder<MethodInfo> candidates = GetMethodCandidates(name, bindingAttr, callConv, types, false);

            if (candidates.Count == 0)
                return null;

            if (types == null || types.Length == 0)
            {
                MethodInfo firstCandidate = candidates[0];

                if (candidates.Count == 1)
                {
                    return firstCandidate;
                }
                else if (types == null)
                {
                    for (int j = 1; j < candidates.Count; j++)
                    {
                        MethodInfo methodInfo = candidates[j];
                        if (!System.DefaultBinder.CompareMethodSig(methodInfo, firstCandidate))
                        {
                            throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
                        }
                    }

                    // All the methods have the exact same name and sig so return the most derived one.
                    return System.DefaultBinder.FindMostDerivedNewSlotMeth(candidates.ToArray(), candidates.Count) as MethodInfo;
                }
            }

            if (binder == null)
                binder = DefaultBinder;

            return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo;
        }


        protected override ConstructorInfo GetConstructorImpl(
            BindingFlags bindingAttr, Binder binder, CallingConventions callConvention,
            Type[] types, ParameterModifier[] modifiers)
        {
            ListBuilder<ConstructorInfo> candidates = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, types, false);

            if (candidates.Count == 0)
                return null;

            if (types.Length == 0 && candidates.Count == 1)
            {
                ConstructorInfo firstCandidate = candidates[0];

                ParameterInfo[] parameters = firstCandidate.GetParametersNoCopy();
                if (parameters == null || parameters.Length == 0)
                {
                    return firstCandidate;
                }
            }

            if ((bindingAttr & BindingFlags.ExactBinding) != 0)
                return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo;

            if (binder == null)
                binder = DefaultBinder;

            return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo;
        }


        protected override PropertyInfo GetPropertyImpl(
            String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
        {
            if (name == null) throw new ArgumentNullException();
            Contract.EndContractBlock();

            ListBuilder<PropertyInfo> candidates = GetPropertyCandidates(name, bindingAttr, types, false);

            if (candidates.Count == 0)
                return null;

            if (types == null || types.Length == 0)
            {
                // no arguments
                if (candidates.Count == 1)
                {
                    PropertyInfo firstCandidate = candidates[0];

                    if ((object)returnType != null && !returnType.IsEquivalentTo(firstCandidate.PropertyType))
                        return null;

                    return firstCandidate;
                }
                else
                {
                    if ((object)returnType == null)
                        // if we are here we have no args or property type to select over and we have more than one property with that name
                        throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
                }
            }

            if ((bindingAttr & BindingFlags.ExactBinding) != 0)
                return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers);

            if (binder == null)
                binder = DefaultBinder;

            return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers);
        }


        public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
        {
            if (name == null) throw new ArgumentNullException();
            Contract.EndContractBlock();

            bool ignoreCase;
            MemberListType listType;
            RuntimeType.FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);

            RuntimeEventInfo[] cache = Cache.GetEventList(listType, name);
            EventInfo match = null;

            bindingAttr ^= BindingFlags.DeclaredOnly;

            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeEventInfo eventInfo = cache[i];
                if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags)
                {
                    if (match != null)
                        throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);

                    match = eventInfo;
                }
            }

            return match;
        }

        public override FieldInfo GetField(String name, BindingFlags bindingAttr)
        {
            if (name == null) throw new ArgumentNullException();
            Contract.EndContractBlock();

            bool ignoreCase;
            MemberListType listType;
            RuntimeType.FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);

            RuntimeFieldInfo[] cache = Cache.GetFieldList(listType, name);
            FieldInfo match = null;

            bindingAttr ^= BindingFlags.DeclaredOnly;
            bool multipleStaticFieldMatches = false;

            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeFieldInfo fieldInfo = cache[i];
                if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags)
                {
                    if (match != null)
                    {
                        if (Object.ReferenceEquals(fieldInfo.DeclaringType, match.DeclaringType))
                            throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);

                        if ((match.DeclaringType.IsInterface == true) && (fieldInfo.DeclaringType.IsInterface == true))
                            multipleStaticFieldMatches = true;
                    }

                    if (match == null || fieldInfo.DeclaringType.IsSubclassOf(match.DeclaringType) || match.DeclaringType.IsInterface)
                        match = fieldInfo;
                }
            }

            if (multipleStaticFieldMatches && match.DeclaringType.IsInterface)
                throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);

            return match;
        }

        public override Type GetInterface(String fullname, bool ignoreCase)
        {
            if (fullname == null) throw new ArgumentNullException();
            Contract.EndContractBlock();

            BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic;

            bindingAttr &= ~BindingFlags.Static;

            if (ignoreCase)
                bindingAttr |= BindingFlags.IgnoreCase;

            string name, ns;
            MemberListType listType;
            SplitName(fullname, out name, out ns);
            RuntimeType.FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);

            RuntimeType[] cache = Cache.GetInterfaceList(listType, name);

            RuntimeType match = null;

            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeType iface = cache[i];
                if (RuntimeType.FilterApplyType(iface, bindingAttr, name, false, ns))
                {
                    if (match != null)
                        throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);

                    match = iface;
                }
            }

            return match;
        }

        public override Type GetNestedType(String fullname, BindingFlags bindingAttr)
        {
            if (fullname == null) throw new ArgumentNullException();
            Contract.EndContractBlock();

            bool ignoreCase;
            bindingAttr &= ~BindingFlags.Static;
            string name, ns;
            MemberListType listType;
            SplitName(fullname, out name, out ns);
            RuntimeType.FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);

            RuntimeType[] cache = Cache.GetNestedTypeList(listType, name);

            RuntimeType match = null;

            for (int i = 0; i < cache.Length; i++)
            {
                RuntimeType nestedType = cache[i];
                if (RuntimeType.FilterApplyType(nestedType, bindingAttr, name, false, ns))
                {
                    if (match != null)
                        throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);

                    match = nestedType;
                }
            }

            return match;
        }

        public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
        {
            if (name == null) throw new ArgumentNullException();
            Contract.EndContractBlock();

            ListBuilder<MethodInfo> methods = new ListBuilder<MethodInfo>();
            ListBuilder<ConstructorInfo> constructors = new ListBuilder<ConstructorInfo>();
            ListBuilder<PropertyInfo> properties = new ListBuilder<PropertyInfo>();
            ListBuilder<EventInfo> events = new ListBuilder<EventInfo>();
            ListBuilder<FieldInfo> fields = new ListBuilder<FieldInfo>();
            ListBuilder<Type> nestedTypes = new ListBuilder<Type>();

            int totalCount = 0;

            // Methods
            if ((type & MemberTypes.Method) != 0)
            {
                methods = GetMethodCandidates(name, bindingAttr, CallingConventions.Any, null, true);
                if (type == MemberTypes.Method)
                    return methods.ToArray();
                totalCount += methods.Count;
            }

            // Constructors
            if ((type & MemberTypes.Constructor) != 0)
            {
                constructors = GetConstructorCandidates(name, bindingAttr, CallingConventions.Any, null, true);
                if (type == MemberTypes.Constructor)
                    return constructors.ToArray();
                totalCount += constructors.Count;
            }

            // Properties
            if ((type & MemberTypes.Property) != 0)
            {
                properties = GetPropertyCandidates(name, bindingAttr, null, true);
                if (type == MemberTypes.Property)
                    return properties.ToArray();
                totalCount += properties.Count;
            }

            // Events
            if ((type & MemberTypes.Event) != 0)
            {
                events = GetEventCandidates(name, bindingAttr, true);
                if (type == MemberTypes.Event)
                    return events.ToArray();
                totalCount += events.Count;
            }

            // Fields
            if ((type & MemberTypes.Field) != 0)
            {
                fields = GetFieldCandidates(name, bindingAttr, true);
                if (type == MemberTypes.Field)
                    return fields.ToArray();
                totalCount += fields.Count;
            }

            // NestedTypes
            if ((type & (MemberTypes.NestedType | MemberTypes.TypeInfo)) != 0)
            {
                nestedTypes = GetNestedTypeCandidates(name, bindingAttr, true);
                if (type == MemberTypes.NestedType || type == MemberTypes.TypeInfo)
                    return nestedTypes.ToArray();
                totalCount += nestedTypes.Count;
            }

            MemberInfo[] compressMembers = (type == (MemberTypes.Method | MemberTypes.Constructor)) ?
                new MethodBase[totalCount] : new MemberInfo[totalCount];

            int i = 0;
            methods.CopyTo(compressMembers, i); i += methods.Count;
            constructors.CopyTo(compressMembers, i); i += constructors.Count;
            properties.CopyTo(compressMembers, i); i += properties.Count;
            events.CopyTo(compressMembers, i); i += events.Count;
            fields.CopyTo(compressMembers, i); i += fields.Count;
            nestedTypes.CopyTo(compressMembers, i); i += nestedTypes.Count;
            Debug.Assert(i == compressMembers.Length);

            return compressMembers;
        }
        #endregion

        #region Identity
        public override Module Module
        {
            get
            {
                return GetRuntimeModule();
            }
        }

        internal RuntimeModule GetRuntimeModule()
        {
            return RuntimeTypeHandle.GetModule(this);
        }

        public override Assembly Assembly
        {
            get
            {
                return GetRuntimeAssembly();
            }
        }

        internal RuntimeAssembly GetRuntimeAssembly()
        {
            return RuntimeTypeHandle.GetAssembly(this);
        }

        public override RuntimeTypeHandle TypeHandle
        {
            get
            {
                return new RuntimeTypeHandle(this);
            }
        }

        internal sealed override RuntimeTypeHandle GetTypeHandleInternal()
        {
            return new RuntimeTypeHandle(this);
        }

        internal bool IsCollectible()
        {
            return RuntimeTypeHandle.IsCollectible(GetTypeHandleInternal());
        }

        protected override TypeCode GetTypeCodeImpl()
        {
            TypeCode typeCode = Cache.TypeCode;

            if (typeCode != TypeCode.Empty)
                return typeCode;

            CorElementType corElementType = RuntimeTypeHandle.GetCorElementType(this);
            switch (corElementType)
            {
                case CorElementType.Boolean:
                    typeCode = TypeCode.Boolean; break;
                case CorElementType.Char:
                    typeCode = TypeCode.Char; break;
                case CorElementType.I1:
                    typeCode = TypeCode.SByte; break;
                case CorElementType.U1:
                    typeCode = TypeCode.Byte; break;
                case CorElementType.I2:
                    typeCode = TypeCode.Int16; break;
                case CorElementType.U2:
                    typeCode = TypeCode.UInt16; break;
                case CorElementType.I4:
                    typeCode = TypeCode.Int32; break;
                case CorElementType.U4:
                    typeCode = TypeCode.UInt32; break;
                case CorElementType.I8:
                    typeCode = TypeCode.Int64; break;
                case CorElementType.U8:
                    typeCode = TypeCode.UInt64; break;
                case CorElementType.R4:
                    typeCode = TypeCode.Single; break;
                case CorElementType.R8:
                    typeCode = TypeCode.Double; break;
                case CorElementType.String:
                    typeCode = TypeCode.String; break;
                case CorElementType.ValueType:
                    if (this == Convert.ConvertTypes[(int)TypeCode.Decimal])
                        typeCode = TypeCode.Decimal;
                    else if (this == Convert.ConvertTypes[(int)TypeCode.DateTime])
                        typeCode = TypeCode.DateTime;
                    else if (this.IsEnum)
                        typeCode = Type.GetTypeCode(Enum.GetUnderlyingType(this));
                    else
                        typeCode = TypeCode.Object;
                    break;
                default:
                    if (this == Convert.ConvertTypes[(int)TypeCode.DBNull])
                        typeCode = TypeCode.DBNull;
                    else if (this == Convert.ConvertTypes[(int)TypeCode.String])
                        typeCode = TypeCode.String;
                    else
                        typeCode = TypeCode.Object;
                    break;
            }

            Cache.TypeCode = typeCode;

            return typeCode;
        }

        public override MethodBase DeclaringMethod
        {
            get
            {
                if (!IsGenericParameter)
                    throw new InvalidOperationException(SR.Arg_NotGenericParameter);
                Contract.EndContractBlock();

                IRuntimeMethodInfo declaringMethod = RuntimeTypeHandle.GetDeclaringMethod(this);

                if (declaringMethod == null)
                    return null;

                return GetMethodBase(RuntimeMethodHandle.GetDeclaringType(declaringMethod), declaringMethod);
            }
        }
        #endregion

        #region Hierarchy
        public override bool IsInstanceOfType(Object o)
        {
            return RuntimeTypeHandle.IsInstanceOfType(this, o);
        }

        [Pure]
        public override bool IsSubclassOf(Type type)
        {
            if ((object)type == null)
                throw new ArgumentNullException(nameof(type));
            Contract.EndContractBlock();
            RuntimeType rtType = type as RuntimeType;
            if (rtType == null)
                return false;

            RuntimeType baseType = GetBaseType();

            while (baseType != null)
            {
                if (baseType == rtType)
                    return true;

                baseType = baseType.GetBaseType();
            }

            // pretty much everything is a subclass of object, even interfaces
            // notice that interfaces are really odd because they do not have a BaseType
            // yet IsSubclassOf(typeof(object)) returns true
            if (rtType == RuntimeType.ObjectType && rtType != this)
                return true;

            return false;
        }

        public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
        {
            if (typeInfo == null) return false;
            return IsAssignableFrom(typeInfo.AsType());
        }

        public override bool IsAssignableFrom(Type c)
        {
            if ((object)c == null)
                return false;

            if (Object.ReferenceEquals(c, this))
                return true;

            RuntimeType fromType = c.UnderlyingSystemType as RuntimeType;

            // For runtime type, let the VM decide.
            if (fromType != null)
            {
                // both this and c (or their underlying system types) are runtime types
                return RuntimeTypeHandle.CanCastTo(fromType, this);
            }

            // Special case for TypeBuilder to be backward-compatible.
            if (c is System.Reflection.Emit.TypeBuilder)
            {
                // If c is a subclass of this class, then c can be cast to this type.
                if (c.IsSubclassOf(this))
                    return true;

                if (this.IsInterface)
                {
                    return c.ImplementInterface(this);
                }
                else if (this.IsGenericParameter)
                {
                    Type[] constraints = GetGenericParameterConstraints();
                    for (int i = 0; i < constraints.Length; i++)
                        if (!constraints[i].IsAssignableFrom(c))
                            return false;

                    return true;
                }
            }

            // For anything else we return false.
            return false;
        }

        public override Type BaseType
        {
            get
            {
                return GetBaseType();
            }
        }

        private RuntimeType GetBaseType()
        {
            if (IsInterface)
                return null;

            if (RuntimeTypeHandle.IsGenericVariable(this))
            {
                Type[] constraints = GetGenericParameterConstraints();

                RuntimeType baseType = RuntimeType.ObjectType;

                for (int i = 0; i < constraints.Length; i++)
                {
                    RuntimeType constraint = (RuntimeType)constraints[i];

                    if (constraint.IsInterface)
                        continue;

                    if (constraint.IsGenericParameter)
                    {
                        GenericParameterAttributes special;
                        special = constraint.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;

                        if ((special & GenericParameterAttributes.ReferenceTypeConstraint) == 0 &&
                            (special & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0)
                            continue;
                    }

                    baseType = constraint;
                }

                if (baseType == RuntimeType.ObjectType)
                {
                    GenericParameterAttributes special;
                    special = GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
                    if ((special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
                        baseType = RuntimeType.ValueType;
                }

                return baseType;
            }

            return RuntimeTypeHandle.GetBaseType(this);
        }

        public override Type UnderlyingSystemType
        {
            get
            {
                return this;
            }
        }
        #endregion

        #region Name
        public override String FullName
        {
            get
            {
                return GetCachedName(TypeNameKind.FullName);
            }
        }

        public override String AssemblyQualifiedName
        {
            get
            {
                string fullname = FullName;

                // FullName is null if this type contains generic parameters but is not a generic type definition.
                if (fullname == null)
                    return null;

                return Assembly.CreateQualifiedName(this.Assembly.FullName, fullname);
            }
        }

        public override String Namespace
        {
            get
            {
                string ns = Cache.GetNameSpace();

                if (ns == null || ns.Length == 0)
                    return null;

                return ns;
            }
        }
        #endregion

        #region Attributes
        protected override TypeAttributes GetAttributeFlagsImpl()
        {
            return RuntimeTypeHandle.GetAttributes(this);
        }

        public override Guid GUID
        {
            get
            {
                Guid result = new Guid();
                GetGUID(ref result);
                return result;
            }
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern void GetGUID(ref Guid result);

        protected override bool IsContextfulImpl()
        {
            return false;
        }

        protected override bool IsByRefImpl()
        {
            return RuntimeTypeHandle.IsByRef(this);
        }

        protected override bool IsPrimitiveImpl()
        {
            return RuntimeTypeHandle.IsPrimitive(this);
        }

        protected override bool IsPointerImpl()
        {
            return RuntimeTypeHandle.IsPointer(this);
        }

        protected override bool IsCOMObjectImpl()
        {
            return RuntimeTypeHandle.IsComObject(this, false);
        }

#if FEATURE_COMINTEROP
        internal override bool IsWindowsRuntimeObjectImpl()
        {
            return IsWindowsRuntimeObjectType(this);
        }

        internal override bool IsExportedToWindowsRuntimeImpl()
        {
            return IsTypeExportedToWindowsRuntime(this);
        }

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern bool IsWindowsRuntimeObjectType(RuntimeType type);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern bool IsTypeExportedToWindowsRuntime(RuntimeType type);

#endif // FEATURE_COMINTEROP

        internal bool IsDelegate()
        {
            return GetBaseType() == typeof(System.MulticastDelegate);
        }

        protected override bool IsValueTypeImpl()
        {
            // We need to return true for generic parameters with the ValueType constraint.
            // So we cannot use the faster RuntimeTypeHandle.IsValueType because it returns 
            // false for all generic parameters.
            if (this == typeof(ValueType) || this == typeof(Enum))
                return false;

            return IsSubclassOf(typeof(ValueType));
        }

        protected override bool HasElementTypeImpl()
        {
            return RuntimeTypeHandle.HasElementType(this);
        }

        public override GenericParameterAttributes GenericParameterAttributes
        {
            get
            {
                if (!IsGenericParameter)
                    throw new InvalidOperationException(SR.Arg_NotGenericParameter);
                Contract.EndContractBlock();

                GenericParameterAttributes attributes;

                RuntimeTypeHandle.GetMetadataImport(this).GetGenericParamProps(MetadataToken, out attributes);

                return attributes;
            }
        }

        public override bool IsSecurityCritical
        {
            get { return new RuntimeTypeHandle(this).IsSecurityCritical(); }
        }
        public override bool IsSecuritySafeCritical
        {
            get { return new RuntimeTypeHandle(this).IsSecuritySafeCritical(); }
        }
        public override bool IsSecurityTransparent
        {
            get { return new RuntimeTypeHandle(this).IsSecurityTransparent(); }
        }
        #endregion

        #region Arrays
        public sealed override bool IsSZArray
        {
            get
            {
                return RuntimeTypeHandle.IsSZArray(this);
            }
        }

        protected override bool IsArrayImpl()
        {
            return RuntimeTypeHandle.IsArray(this);
        }

        public override int GetArrayRank()
        {
            if (!IsArrayImpl())
                throw new ArgumentException(SR.Argument_HasToBeArrayClass);

            return RuntimeTypeHandle.GetArrayRank(this);
        }

        public override Type GetElementType()
        {
            return RuntimeTypeHandle.GetElementType(this);
        }
        #endregion

        #region Enums
        public override string[] GetEnumNames()
        {
            if (!IsEnum)
                throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
            Contract.EndContractBlock();

            String[] ret = Enum.InternalGetNames(this);

            // Make a copy since we can't hand out the same array since users can modify them
            String[] retVal = new String[ret.Length];

            Array.Copy(ret, retVal, ret.Length);

            return retVal;
        }

        public override Array GetEnumValues()
        {
            if (!IsEnum)
                throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
            Contract.EndContractBlock();

            // Get all of the values
            ulong[] values = Enum.InternalGetValues(this);

            // Create a generic Array
            Array ret = Array.UnsafeCreateInstance(this, values.Length);

            for (int i = 0; i < values.Length; i++)
            {
                Object val = Enum.ToObject(this, values[i]);
                ret.SetValue(val, i);
            }

            return ret;
        }

        public override Type GetEnumUnderlyingType()
        {
            if (!IsEnum)
                throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
            Contract.EndContractBlock();

            return Enum.InternalGetUnderlyingType(this);
        }

        public override bool IsEnumDefined(object value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));
            Contract.EndContractBlock();

            // Check if both of them are of the same type
            RuntimeType valueType = (RuntimeType)value.GetType();

            // If the value is an Enum then we need to extract the underlying value from it
            if (valueType.IsEnum)
            {
                if (!valueType.IsEquivalentTo(this))
                    throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType.ToString(), this.ToString()));

                valueType = (RuntimeType)valueType.GetEnumUnderlyingType();
            }

            // If a string is passed in
            if (valueType == RuntimeType.StringType)
            {
                // Get all of the Fields, calling GetHashEntry directly to avoid copying
                string[] names = Enum.InternalGetNames(this);
                if (Array.IndexOf(names, value) >= 0)
                    return true;
                else
                    return false;
            }

            // If an enum or integer value is passed in
            if (Type.IsIntegerType(valueType))
            {
                RuntimeType underlyingType = Enum.InternalGetUnderlyingType(this);
                if (underlyingType != valueType)
                    throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, valueType.ToString(), underlyingType.ToString()));

                ulong[] ulValues = Enum.InternalGetValues(this);
                ulong ulValue = Enum.ToUInt64(value);

                return (Array.BinarySearch(ulValues, ulValue) >= 0);
            }
            else
            {
                throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
            }
        }

        public override string GetEnumName(object value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));
            Contract.EndContractBlock();

            Type valueType = value.GetType();

            if (!(valueType.IsEnum || IsIntegerType(valueType)))
                throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));

            ulong ulValue = Enum.ToUInt64(value);

            return Enum.GetEnumName(this, ulValue);
        }
        #endregion

        #region Generics
        internal RuntimeType[] GetGenericArgumentsInternal()
        {
            return GetRootElementType().GetTypeHandleInternal().GetInstantiationInternal();
        }

        public override Type[] GetGenericArguments()
        {
            Type[] types = GetRootElementType().GetTypeHandleInternal().GetInstantiationPublic();

            if (types == null)
                types = Array.Empty<Type>();

            return types;
        }

        public override Type MakeGenericType(Type[] instantiation)
        {
            if (instantiation == null)
                throw new ArgumentNullException(nameof(instantiation));
            Contract.EndContractBlock();

            RuntimeType[] instantiationRuntimeType = new RuntimeType[instantiation.Length];

            if (!IsGenericTypeDefinition)
                throw new InvalidOperationException(
                    SR.Format(SR.Arg_NotGenericTypeDefinition, this));

            if (GetGenericArguments().Length != instantiation.Length)
                throw new ArgumentException(SR.Argument_GenericArgsCount, nameof(instantiation));

            for (int i = 0; i < instantiation.Length; i++)
            {
                Type instantiationElem = instantiation[i];
                if (instantiationElem == null)
                    throw new ArgumentNullException();

                RuntimeType rtInstantiationElem = instantiationElem as RuntimeType;

                if (rtInstantiationElem == null)
                {
                    Type[] instantiationCopy = new Type[instantiation.Length];
                    for (int iCopy = 0; iCopy < instantiation.Length; iCopy++)
                        instantiationCopy[iCopy] = instantiation[iCopy];
                    instantiation = instantiationCopy;
                    return System.Reflection.Emit.TypeBuilderInstantiation.MakeGenericType(this, instantiation);
                }

                instantiationRuntimeType[i] = rtInstantiationElem;
            }

            RuntimeType[] genericParameters = GetGenericArgumentsInternal();

            SanityCheckGenericArguments(instantiationRuntimeType, genericParameters);

            Type ret = null;
            try
            {
                ret = new RuntimeTypeHandle(this).Instantiate(instantiationRuntimeType);
            }
            catch (TypeLoadException e)
            {
                ValidateGenericArguments(this, instantiationRuntimeType, e);
                throw e;
            }

            return ret;
        }

        public override bool IsGenericTypeDefinition
        {
            get { return RuntimeTypeHandle.IsGenericTypeDefinition(this); }
        }

        public override bool IsGenericParameter
        {
            get { return RuntimeTypeHandle.IsGenericVariable(this); }
        }

        public override int GenericParameterPosition
        {
            get
            {
                if (!IsGenericParameter)
                    throw new InvalidOperationException(SR.Arg_NotGenericParameter);
                Contract.EndContractBlock();

                return new RuntimeTypeHandle(this).GetGenericVariableIndex();
            }
        }

        public override Type GetGenericTypeDefinition()
        {
            if (!IsGenericType)
                throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
            Contract.EndContractBlock();

            return RuntimeTypeHandle.GetGenericTypeDefinition(this);
        }

        public override bool IsGenericType
        {
            get { return RuntimeTypeHandle.HasInstantiation(this); }
        }

        public override bool IsConstructedGenericType
        {
            get { return IsGenericType && !IsGenericTypeDefinition; }
        }

        public override bool ContainsGenericParameters
        {
            get { return GetRootElementType().GetTypeHandleInternal().ContainsGenericVariables(); }
        }

        public override Type[] GetGenericParameterConstraints()
        {
            if (!IsGenericParameter)
                throw new InvalidOperationException(SR.Arg_NotGenericParameter);
            Contract.EndContractBlock();

            Type[] constraints = new RuntimeTypeHandle(this).GetConstraints();

            if (constraints == null)
                constraints = Array.Empty<Type>();

            return constraints;
        }
        #endregion

        #region Misc
        public override Type MakePointerType() { return new RuntimeTypeHandle(this).MakePointer(); }
        public override Type MakeByRefType() { return new RuntimeTypeHandle(this).MakeByRef(); }
        public override Type MakeArrayType() { return new RuntimeTypeHandle(this).MakeSZArray(); }
        public override Type MakeArrayType(int rank)
        {
            if (rank <= 0)
                throw new IndexOutOfRangeException();
            Contract.EndContractBlock();

            return new RuntimeTypeHandle(this).MakeArray(rank);
        }
        public override StructLayoutAttribute StructLayoutAttribute
        {
            get
            {
                return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute(this);
            }
        }
        #endregion

        #region Invoke Member
        private const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF;
        private const BindingFlags InvocationMask = (BindingFlags)0x0000FF00;
        private const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty;
        private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty;
        private const BindingFlags BinderSetInvokeProperty = BindingFlags.InvokeMethod | BindingFlags.SetProperty;
        private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField;
        private const BindingFlags BinderSetInvokeField = BindingFlags.SetField | BindingFlags.InvokeMethod;
        private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300;
        private const BindingFlags ClassicBindingMask =
            BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty |
            BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty;
        private static RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        static private extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        static private extern Object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange);

        internal unsafe Object CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
        {
            // this method is used by invocation in reflection to check whether a value can be assigned to type.
            if (IsInstanceOfType(value))
            {
                // Since this cannot be a generic parameter, we use RuntimeTypeHandle.IsValueType here
                // because it is faster than RuntimeType.IsValueType
                Debug.Assert(!IsGenericParameter);

                Type type = value.GetType();

                if (!Object.ReferenceEquals(type, this) && RuntimeTypeHandle.IsValueType(this))
                {
                    // must be an equivalent type, re-box to the target type
                    return AllocateValueType(this, value, true);
                }
                else
                {
                    return value;
                }
            }

            // if this is a ByRef get the element type and check if it's compatible
            bool isByRef = IsByRef;
            if (isByRef)
            {
                RuntimeType elementType = RuntimeTypeHandle.GetElementType(this);
                if (elementType.IsInstanceOfType(value) || value == null)
                {
                    // need to create an instance of the ByRef if null was provided, but only if primitive, enum or value type
                    return AllocateValueType(elementType, value, false);
                }
            }
            else if (value == null)
                return value;
            else if (this == s_typedRef)
                // everything works for a typedref
                return value;

            // check the strange ones courtesy of reflection:
            // - implicit cast between primitives
            // - enum treated as underlying type
            // - IntPtr and System.Reflection.Pointer to pointer types
            bool needsSpecialCast = IsPointer || IsEnum || IsPrimitive;
            if (needsSpecialCast)
            {
                RuntimeType valueType;
                Pointer pointer = value as Pointer;
                if (pointer != null)
                    valueType = (RuntimeType)pointer.GetPointerType();
                else
                    valueType = (RuntimeType)value.GetType();

                if (CanValueSpecialCast(valueType, this))
                {
                    if (pointer != null)
                        return pointer.GetPointerValue();
                    else
                        return value;
                }
            }

            if ((invokeAttr & BindingFlags.ExactBinding) == BindingFlags.ExactBinding)
                throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, SR.Arg_ObjObjEx, value.GetType(), this));

            return TryChangeType(value, binder, culture, needsSpecialCast);
        }

        // Factored out of CheckValue to reduce code complexity.
        private Object TryChangeType(Object value, Binder binder, CultureInfo culture, bool needsSpecialCast)
        {
            if (binder != null && binder != Type.DefaultBinder)
            {
                value = binder.ChangeType(value, this, culture);
                if (IsInstanceOfType(value))
                    return value;
                // if this is a ByRef get the element type and check if it's compatible
                if (IsByRef)
                {
                    RuntimeType elementType = RuntimeTypeHandle.GetElementType(this);
                    if (elementType.IsInstanceOfType(value) || value == null)
                        return AllocateValueType(elementType, value, false);
                }
                else if (value == null)
                    return value;
                if (needsSpecialCast)
                {
                    RuntimeType valueType;
                    Pointer pointer = value as Pointer;
                    if (pointer != null)
                        valueType = (RuntimeType)pointer.GetPointerType();
                    else
                        valueType = (RuntimeType)value.GetType();

                    if (CanValueSpecialCast(valueType, this))
                    {
                        if (pointer != null)
                            return pointer.GetPointerValue();
                        else
                            return value;
                    }
                }
            }

            throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, SR.Arg_ObjObjEx, value.GetType(), this));
        }

        // GetDefaultMembers
        // This will return a MemberInfo that has been marked with the [DefaultMemberAttribute]
        public override MemberInfo[] GetDefaultMembers()
        {
            // See if we have cached the default member name
            MemberInfo[] members = null;

            String defaultMemberName = GetDefaultMemberName();
            if (defaultMemberName != null)
            {
                members = GetMember(defaultMemberName);
            }

            if (members == null)
                members = Array.Empty<MemberInfo>();

            return members;
        }

#if FEATURE_COMINTEROP
#endif
        [DebuggerStepThroughAttribute]
        [Diagnostics.DebuggerHidden]
        public override Object InvokeMember(
            String name, BindingFlags bindingFlags, Binder binder, Object target,
            Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
        {
            if (IsGenericParameter)
                throw new InvalidOperationException(SR.Arg_GenericParameter);
            Contract.EndContractBlock();

            #region Preconditions
            if ((bindingFlags & InvocationMask) == 0)
                // "Must specify binding flags describing the invoke operation required."
                throw new ArgumentException(SR.Arg_NoAccessSpec, nameof(bindingFlags));

            // Provide a default binding mask if none is provided 
            if ((bindingFlags & MemberBindingMask) == 0)
            {
                bindingFlags |= BindingFlags.Instance | BindingFlags.Public;

                if ((bindingFlags & BindingFlags.CreateInstance) == 0)
                    bindingFlags |= BindingFlags.Static;
            }

            // There must not be more named parameters than provided arguments
            if (namedParams != null)
            {
                if (providedArgs != null)
                {
                    if (namedParams.Length > providedArgs.Length)
                        // "Named parameter array can not be bigger than argument array."
                        throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
                }
                else
                {
                    if (namedParams.Length != 0)
                        // "Named parameter array can not be bigger than argument array."
                        throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
                }
            }
            #endregion

            #region COM Interop
#if FEATURE_COMINTEROP && FEATURE_USE_LCID
            if (target != null && target.GetType().IsCOMObject)
            {
                #region Preconditions
                if ((bindingFlags & ClassicBindingMask) == 0)
                    throw new ArgumentException(SR.Arg_COMAccess, nameof(bindingFlags));

                if ((bindingFlags & BindingFlags.GetProperty) != 0 && (bindingFlags & ClassicBindingMask & ~(BindingFlags.GetProperty | BindingFlags.InvokeMethod)) != 0)
                    throw new ArgumentException(SR.Arg_PropSetGet, nameof(bindingFlags));

                if ((bindingFlags & BindingFlags.InvokeMethod) != 0 && (bindingFlags & ClassicBindingMask & ~(BindingFlags.GetProperty | BindingFlags.InvokeMethod)) != 0)
                    throw new ArgumentException(SR.Arg_PropSetInvoke, nameof(bindingFlags));

                if ((bindingFlags & BindingFlags.SetProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.SetProperty) != 0)
                    throw new ArgumentException(SR.Arg_COMPropSetPut, nameof(bindingFlags));

                if ((bindingFlags & BindingFlags.PutDispProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.PutDispProperty) != 0)
                    throw new ArgumentException(SR.Arg_COMPropSetPut, nameof(bindingFlags));

                if ((bindingFlags & BindingFlags.PutRefDispProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.PutRefDispProperty) != 0)
                    throw new ArgumentException(SR.Arg_COMPropSetPut, nameof(bindingFlags));
                #endregion

                {
                    #region Non-TransparentProxy case
                    if (name == null)
                        throw new ArgumentNullException(nameof(name));

                    bool[] isByRef = modifiers == null ? null : modifiers[0].IsByRefArray;

                    // pass LCID_ENGLISH_US if no explicit culture is specified to match the behavior of VB
                    int lcid = (culture == null ? 0x0409 : culture.LCID);

                    return InvokeDispMethod(name, bindingFlags, target, providedArgs, isByRef, lcid, namedParams);
                    #endregion
                }
            }
#endif // FEATURE_COMINTEROP && FEATURE_USE_LCID
            #endregion

            #region Check that any named paramters are not null
            if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
                // "Named parameter value must not be null."
                throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams));
            #endregion

            int argCnt = (providedArgs != null) ? providedArgs.Length : 0;

            #region Get a Binder
            if (binder == null)
                binder = DefaultBinder;

            bool bDefaultBinder = (binder == DefaultBinder);
            #endregion

            #region Delegate to Activator.CreateInstance
            if ((bindingFlags & BindingFlags.CreateInstance) != 0)
            {
                if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0)
                    // "Can not specify both CreateInstance and another access type."
                    throw new ArgumentException(SR.Arg_CreatInstAccess, nameof(bindingFlags));

                return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
            }
            #endregion

            // PutDispProperty and\or PutRefDispProperty ==> SetProperty.
            if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0)
                bindingFlags |= BindingFlags.SetProperty;

            #region Name
            if (name == null)
                throw new ArgumentNullException(nameof(name));

            if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
            {
                name = GetDefaultMemberName();

                if (name == null)
                {
                    // in InvokeMember we always pretend there is a default member if none is provided and we make it ToString
                    name = "ToString";
                }
            }
            #endregion

            #region GetField or SetField
            bool IsGetField = (bindingFlags & BindingFlags.GetField) != 0;
            bool IsSetField = (bindingFlags & BindingFlags.SetField) != 0;

            if (IsGetField || IsSetField)
            {
                #region Preconditions
                if (IsGetField)
                {
                    if (IsSetField)
                        // "Can not specify both Get and Set on a field."
                        throw new ArgumentException(SR.Arg_FldSetGet, nameof(bindingFlags));

                    if ((bindingFlags & BindingFlags.SetProperty) != 0)
                        // "Can not specify both GetField and SetProperty."
                        throw new ArgumentException(SR.Arg_FldGetPropSet, nameof(bindingFlags));
                }
                else
                {
                    Debug.Assert(IsSetField);

                    if (providedArgs == null)
                        throw new ArgumentNullException(nameof(providedArgs));

                    if ((bindingFlags & BindingFlags.GetProperty) != 0)
                        // "Can not specify both SetField and GetProperty."
                        throw new ArgumentException(SR.Arg_FldSetPropGet, nameof(bindingFlags));

                    if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
                        // "Can not specify Set on a Field and Invoke on a method."
                        throw new ArgumentException(SR.Arg_FldSetInvoke, nameof(bindingFlags));
                }
                #endregion

                #region Lookup Field
                FieldInfo selFld = null;
                FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];

                Debug.Assert(flds != null);

                if (flds.Length == 1)
                {
                    selFld = flds[0];
                }
                else if (flds.Length > 0)
                {
                    selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture);
                }
                #endregion

                if (selFld != null)
                {
                    #region Invocation on a field
                    if (selFld.FieldType.IsArray || Object.ReferenceEquals(selFld.FieldType, typeof(System.Array)))
                    {
                        #region Invocation of an array Field
                        int idxCnt;

                        if ((bindingFlags & BindingFlags.GetField) != 0)
                        {
                            idxCnt = argCnt;
                        }
                        else
                        {
                            idxCnt = argCnt - 1;
                        }

                        if (idxCnt > 0)
                        {
                            // Verify that all of the index values are ints
                            int[] idx = new int[idxCnt];
                            for (int i = 0; i < idxCnt; i++)
                            {
                                try
                                {
                                    idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null);
                                }
                                catch (InvalidCastException)
                                {
                                    throw new ArgumentException(SR.Arg_IndexMustBeInt);
                                }
                            }

                            // Set or get the value...
                            Array a = (Array)selFld.GetValue(target);

                            // Set or get the value in the array
                            if ((bindingFlags & BindingFlags.GetField) != 0)
                            {
                                return a.GetValue(idx);
                            }
                            else
                            {
                                a.SetValue(providedArgs[idxCnt], idx);
                                return null;
                            }
                        }
                        #endregion
                    }

                    if (IsGetField)
                    {
                        #region Get the field value
                        if (argCnt != 0)
                            throw new ArgumentException(SR.Arg_FldGetArgErr, nameof(bindingFlags));

                        return selFld.GetValue(target);
                        #endregion
                    }
                    else
                    {
                        #region Set the field Value
                        if (argCnt != 1)
                            throw new ArgumentException(SR.Arg_FldSetArgErr, nameof(bindingFlags));

                        selFld.SetValue(target, providedArgs[0], bindingFlags, binder, culture);

                        return null;
                        #endregion
                    }
                    #endregion
                }

                if ((bindingFlags & BinderNonFieldGetSet) == 0)
                    throw new MissingFieldException(FullName, name);
            }
            #endregion                    

            #region Caching Logic
            /*
            bool useCache = false;

            // Note that when we add something to the cache, we are careful to ensure
            // that the actual providedArgs matches the parameters of the method.  Otherwise,
            // some default argument processing has occurred.  We don't want anyone
            // else with the same (insufficient) number of actual arguments to get a
            // cache hit because then they would bypass the default argument processing
            // and the invocation would fail.
            if (bDefaultBinder && namedParams == null && argCnt < 6)
                useCache = true;

            if (useCache)
            {
                MethodBase invokeMethod = GetMethodFromCache (name, bindingFlags, argCnt, providedArgs);

                if (invokeMethod != null)
                    return ((MethodInfo) invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture);
            }
            */
            #endregion

            #region Property PreConditions
            // @Legacy - This is RTM behavior
            bool isGetProperty = (bindingFlags & BindingFlags.GetProperty) != 0;
            bool isSetProperty = (bindingFlags & BindingFlags.SetProperty) != 0;

            if (isGetProperty || isSetProperty)
            {
                #region Preconditions
                if (isGetProperty)
                {
                    Debug.Assert(!IsSetField);

                    if (isSetProperty)
                        throw new ArgumentException(SR.Arg_PropSetGet, nameof(bindingFlags));
                }
                else
                {
                    Debug.Assert(isSetProperty);

                    Debug.Assert(!IsGetField);

                    if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
                        throw new ArgumentException(SR.Arg_PropSetInvoke, nameof(bindingFlags));
                }
                #endregion
            }
            #endregion

            MethodInfo[] finalists = null;
            MethodInfo finalist = null;

            #region BindingFlags.InvokeMethod
            if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
            {
                #region Lookup Methods
                MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[];
                List<MethodInfo> results = null;

                for (int i = 0; i < semiFinalists.Length; i++)
                {
                    MethodInfo semiFinalist = semiFinalists[i];
                    Debug.Assert(semiFinalist != null);

                    if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
                        continue;

                    if (finalist == null)
                    {
                        finalist = semiFinalist;
                    }
                    else
                    {
                        if (results == null)
                        {
                            results = new List<MethodInfo>(semiFinalists.Length);
                            results.Add(finalist);
                        }

                        results.Add(semiFinalist);
                    }
                }

                if (results != null)
                {
                    Debug.Assert(results.Count > 1);
                    finalists = new MethodInfo[results.Count];
                    results.CopyTo(finalists);
                }
                #endregion
            }
            #endregion

            Debug.Assert(finalists == null || finalist != null);

            #region BindingFlags.GetProperty or BindingFlags.SetProperty
            if (finalist == null && isGetProperty || isSetProperty)
            {
                #region Lookup Property
                PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[];
                List<MethodInfo> results = null;

                for (int i = 0; i < semiFinalists.Length; i++)
                {
                    MethodInfo semiFinalist = null;

                    if (isSetProperty)
                    {
                        semiFinalist = semiFinalists[i].GetSetMethod(true);
                    }
                    else
                    {
                        semiFinalist = semiFinalists[i].GetGetMethod(true);
                    }

                    if (semiFinalist == null)
                        continue;

                    if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
                        continue;

                    if (finalist == null)
                    {
                        finalist = semiFinalist;
                    }
                    else
                    {
                        if (results == null)
                        {
                            results = new List<MethodInfo>(semiFinalists.Length);
                            results.Add(finalist);
                        }

                        results.Add(semiFinalist);
                    }
                }

                if (results != null)
                {
                    Debug.Assert(results.Count > 1);
                    finalists = new MethodInfo[results.Count];
                    results.CopyTo(finalists);
                }
                #endregion            
            }
            #endregion

            if (finalist != null)
            {
                #region Invoke
                if (finalists == null &&
                    argCnt == 0 &&
                    finalist.GetParametersNoCopy().Length == 0 &&
                    (bindingFlags & BindingFlags.OptionalParamBinding) == 0)
                {
                    //if (useCache && argCnt == props[0].GetParameters().Length)
                    //    AddMethodToCache(name, bindingFlags, argCnt, providedArgs, props[0]);

                    return finalist.Invoke(target, bindingFlags, binder, providedArgs, culture);
                }

                if (finalists == null)
                    finalists = new MethodInfo[] { finalist };

                if (providedArgs == null)
                    providedArgs = Array.Empty<Object>();

                Object state = null;


                MethodBase invokeMethod = null;

                try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); }
                catch (MissingMethodException) { }

                if (invokeMethod == null)
                    throw new MissingMethodException(FullName, name);

                //if (useCache && argCnt == invokeMethod.GetParameters().Length)
                //    AddMethodToCache(name, bindingFlags, argCnt, providedArgs, invokeMethod);

                Object result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture);

                if (state != null)
                    binder.ReorderArgumentArray(ref providedArgs, state);

                return result;
                #endregion
            }

            throw new MissingMethodException(FullName, name);
        }
        #endregion

        #endregion

        #region Object Overrides
        [Pure]
        public override bool Equals(object obj)
        {
            // ComObjects are identified by the instance of the Type object and not the TypeHandle.
            return obj == (object)this;
        }

        public override int GetHashCode()
        {
            return RuntimeHelpers.GetHashCode(this);
        }

        public override String ToString()
        {
            return GetCachedName(TypeNameKind.ToString);
        }
        #endregion

        #region ICloneable
        public Object Clone()
        {
            return this;
        }
        #endregion

        #region ISerializable
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException(nameof(info));
            Contract.EndContractBlock();

            UnitySerializationHolder.GetUnitySerializationInfo(info, this);
        }
        #endregion

        #region ICustomAttributeProvider
        public override Object[] GetCustomAttributes(bool inherit)
        {
            return CustomAttribute.GetCustomAttributes(this, RuntimeType.ObjectType, inherit);
        }

        public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
        {
            if ((object)attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));
            Contract.EndContractBlock();

            RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;

            if (attributeRuntimeType == null)
                throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));

            return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
        }

        public override bool IsDefined(Type attributeType, bool inherit)
        {
            if ((object)attributeType == null)
                throw new ArgumentNullException(nameof(attributeType));
            Contract.EndContractBlock();

            RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;

            if (attributeRuntimeType == null)
                throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));

            return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
        }

        public override IList<CustomAttributeData> GetCustomAttributesData()
        {
            return CustomAttributeData.GetCustomAttributesInternal(this);
        }
        #endregion

        #region MemberInfo Overrides
        public override String Name
        {
            get
            {
                return GetCachedName(TypeNameKind.Name);
            }
        }

        // This is used by the ToString() overrides of all reflection types. The legacy behavior has the following problems:
        //  1. Use only Name for nested types, which can be confused with global types and generic parameters of the same name.
        //  2. Use only Name for generic parameters, which can be confused with nested types and global types of the same name.
        //  3. Remove the namespace ("System") for all primitive types, which is not language neutral.
        //  4. MethodBase.ToString() use "ByRef" for byref parameters which is different than Type.ToString().
        //  5. ConstructorInfo.ToString() outputs "Void" as the return type. Why Void?
        // Since it could be a breaking changes to fix these legacy behaviors, we only use the better and more unambiguous format
        // in serialization (MemberInfoSerializationHolder).
        internal override string FormatTypeName(bool serialization)
        {
            if (serialization)
            {
                return GetCachedName(TypeNameKind.SerializationName);
            }
            else
            {
                Type elementType = GetRootElementType();

                // Legacy: this doesn't make sense, why use only Name for nested types but otherwise
                // ToString() which contains namespace.
                if (elementType.IsNested)
                    return Name;

                string typeName = ToString();

                // Legacy: why removing "System"? Is it just because C# has keywords for these types?
                // If so why don't we change it to lower case to match the C# keyword casing?
                if (elementType.IsPrimitive ||
                    elementType == typeof(void) ||
                    elementType == typeof(TypedReference))
                {
                    typeName = typeName.Substring(@"System.".Length);
                }

                return typeName;
            }
        }

        private string GetCachedName(TypeNameKind kind)
        {
            return Cache.GetName(kind);
        }

        public override MemberTypes MemberType
        {
            get
            {
                if (this.IsPublic || this.IsNotPublic)
                    return MemberTypes.TypeInfo;
                else
                    return MemberTypes.NestedType;
            }
        }

        public override Type DeclaringType
        {
            get
            {
                return Cache.GetEnclosingType();
            }
        }

        public override Type ReflectedType
        {
            get
            {
                return DeclaringType;
            }
        }

        public override int MetadataToken
        {
            get
            {
                return RuntimeTypeHandle.GetToken(this);
            }
        }
        #endregion

        #region Legacy Internal
        private void CreateInstanceCheckThis()
        {
            if (this is ReflectionOnlyType)
                throw new ArgumentException(SR.Arg_ReflectionOnlyInvoke);

            if (ContainsGenericParameters)
                throw new ArgumentException(
                    SR.Format(SR.Acc_CreateGenericEx, this));
            Contract.EndContractBlock();

            Type elementType = this.GetRootElementType();

            if (Object.ReferenceEquals(elementType, typeof(ArgIterator)))
                throw new NotSupportedException(SR.Acc_CreateArgIterator);

            if (Object.ReferenceEquals(elementType, typeof(void)))
                throw new NotSupportedException(SR.Acc_CreateVoid);
        }

        internal Object CreateInstanceImpl(
            BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, ref StackCrawlMark stackMark)
        {
            CreateInstanceCheckThis();

            Object server = null;

            if (args == null)
                args = Array.Empty<Object>();

            int argCnt = args.Length;

            // Without a binder we need to do use the default binder...
            if (binder == null)
                binder = DefaultBinder;

            // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
            // so a call to GetMemberCons would fail
            if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0
                && (IsGenericCOMObjectImpl() || IsValueType))
            {
                server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0, false, true, ref stackMark);
            }
            else
            {
                ConstructorInfo[] candidates = GetConstructors(bindingAttr);
                List<MethodBase> matches = new List<MethodBase>(candidates.Length);

                // We cannot use Type.GetTypeArray here because some of the args might be null
                Type[] argsType = new Type[argCnt];
                for (int i = 0; i < argCnt; i++)
                {
                    if (args[i] != null)
                    {
                        argsType[i] = args[i].GetType();
                    }
                }

                for (int i = 0; i < candidates.Length; i++)
                {
                    if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType))
                        matches.Add(candidates[i]);
                }

                MethodBase[] cons = new MethodBase[matches.Count];
                matches.CopyTo(cons);
                if (cons != null && cons.Length == 0)
                    cons = null;

                if (cons == null)
                {
                    throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName));
                }

                MethodBase invokeMethod;
                Object state = null;

                try
                {
                    invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state);
                }
                catch (MissingMethodException) { invokeMethod = null; }

                if (invokeMethod == null)
                {
                    throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName));
                }

                if (invokeMethod.GetParametersNoCopy().Length == 0)
                {
                    if (args.Length != 0)
                    {
                        Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
                                            CallingConventions.VarArgs);
                        throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
                            SR.NotSupported_CallToVarArg));
                    }

                    // fast path??
                    server = Activator.CreateInstance(this, true);
                }
                else
                {
                    server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture);
                    if (state != null)
                        binder.ReorderArgumentArray(ref args, state);
                }
            }

            return server;
        }

        // the cache entry
        private class ActivatorCacheEntry
        {
            // the type to cache
            internal readonly RuntimeType m_type;
            // the delegate containing the call to the ctor, will be replaced by an IntPtr to feed a calli with
            internal volatile CtorDelegate m_ctor;
            internal readonly RuntimeMethodHandleInternal m_hCtorMethodHandle;
            internal readonly MethodAttributes m_ctorAttributes;
            // Lazy initialization was performed
            internal volatile bool m_bFullyInitialized;

            internal ActivatorCacheEntry(RuntimeType t, RuntimeMethodHandleInternal rmh)
            {
                m_type = t;
                m_hCtorMethodHandle = rmh;
                if (!m_hCtorMethodHandle.IsNullHandle())
                    m_ctorAttributes = RuntimeMethodHandle.GetAttributes(m_hCtorMethodHandle);
            }
        }

        //ActivatorCache
        private class ActivatorCache
        {
            private const int CACHE_SIZE = 16;
            private volatile int hash_counter; //Counter for wrap around
            private readonly ActivatorCacheEntry[] cache = new ActivatorCacheEntry[CACHE_SIZE];

            private volatile ConstructorInfo delegateCtorInfo;

            private void InitializeDelegateCreator()
            {
                ConstructorInfo ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] { typeof(Object), typeof(IntPtr) });
                delegateCtorInfo = ctorInfo; // this assignment should be last
            }

            private void InitializeCacheEntry(ActivatorCacheEntry ace)
            {
                if (!ace.m_type.IsValueType)
                {
                    Debug.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");

                    if (delegateCtorInfo == null)
                        InitializeDelegateCreator();

                    // No synchronization needed here. In the worst case we create extra garbage
                    CtorDelegate ctor = (CtorDelegate)delegateCtorInfo.Invoke(new Object[] { null, RuntimeMethodHandle.GetFunctionPointer(ace.m_hCtorMethodHandle) });
                    ace.m_ctor = ctor;
                }
                ace.m_bFullyInitialized = true;
            }

            internal ActivatorCacheEntry GetEntry(RuntimeType t)
            {
                int index = hash_counter;
                for (int i = 0; i < CACHE_SIZE; i++)
                {
                    ActivatorCacheEntry ace = Volatile.Read(ref cache[index]);
                    if (ace != null && ace.m_type == t) //check for type match..
                    {
                        if (!ace.m_bFullyInitialized)
                            InitializeCacheEntry(ace);
                        return ace;
                    }
                    index = (index + 1) & (ActivatorCache.CACHE_SIZE - 1);
                }
                return null;
            }

            internal void SetEntry(ActivatorCacheEntry ace)
            {
                // fill the the array backwards to hit the most recently filled entries first in GetEntry
                int index = (hash_counter - 1) & (ActivatorCache.CACHE_SIZE - 1);
                hash_counter = index;
                Volatile.Write(ref cache[index], ace);
            }
        }

        private static volatile ActivatorCache s_ActivatorCache;

        // the slow path of CreateInstanceDefaultCtor
        internal Object CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
        {
            RuntimeMethodHandleInternal runtime_ctor = default(RuntimeMethodHandleInternal);
            bool bCanBeCached = false;

            if (!skipCheckThis)
                CreateInstanceCheckThis();

            Object instance = RuntimeTypeHandle.CreateInstance(this, publicOnly, ref bCanBeCached, ref runtime_ctor);

            if (bCanBeCached && fillCache)
            {
                ActivatorCache activatorCache = s_ActivatorCache;
                if (activatorCache == null)
                {
                    // No synchronization needed here. In the worst case we create extra garbage
                    activatorCache = new ActivatorCache();
                    s_ActivatorCache = activatorCache;
                }

                // cache the ctor
                ActivatorCacheEntry ace = new ActivatorCacheEntry(this, runtime_ctor);
                activatorCache.SetEntry(ace);
            }

            return instance;
        }

        // Helper to invoke the default (parameterless) ctor.
        // fillCache is set in the SL2/3 compat mode or when called from Marshal.PtrToStructure.
        [DebuggerStepThroughAttribute]
        [Diagnostics.DebuggerHidden]
        internal Object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
        {
            if (GetType() == typeof(ReflectionOnlyType))
                throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);

            ActivatorCache activatorCache = s_ActivatorCache;
            if (activatorCache != null)
            {
                ActivatorCacheEntry ace = activatorCache.GetEntry(this);
                if (ace != null)
                {
                    if (publicOnly)
                    {
                        if (ace.m_ctor != null &&
                            (ace.m_ctorAttributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
                        {
                            throw new MissingMethodException(SR.Arg_NoDefCTor);
                        }
                    }

                    // Allocate empty object
                    Object instance = RuntimeTypeHandle.Allocate(this);

                    // if m_ctor is null, this type doesn't have a default ctor
                    Debug.Assert(ace.m_ctor != null || this.IsValueType);

                    if (ace.m_ctor != null)
                    {
                        // Call ctor (value types wont have any)
                        try
                        {
                            ace.m_ctor(instance);
                        }
                        catch (Exception e)
                        {
                            throw new TargetInvocationException(e);
                        }
                    }
                    return instance;
                }
            }
            return CreateInstanceSlow(publicOnly, skipCheckThis, fillCache, ref stackMark);
        }

        internal void InvalidateCachedNestedType()
        {
            Cache.InvalidateCachedNestedType();
        }

        internal bool IsGenericCOMObjectImpl()
        {
            return RuntimeTypeHandle.IsComObject(this, true);
        }
        #endregion

        #region Legacy Static Internal
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern Object _CreateEnum(RuntimeType enumType, long value);
        internal static Object CreateEnum(RuntimeType enumType, long value)
        {
            return _CreateEnum(enumType, value);
        }

#if FEATURE_COMINTEROP       
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private extern Object InvokeDispMethod(
            String name, BindingFlags invokeAttr, Object target, Object[] args,
            bool[] byrefModifiers, int culture, String[] namedParameters);
#endif // FEATURE_COMINTEROP        

#if FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern Type GetTypeFromProgIDImpl(String progID, String server, bool throwOnError);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        internal static extern Type GetTypeFromCLSIDImpl(Guid clsid, String server, bool throwOnError);
#else // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
        internal static Type GetTypeFromProgIDImpl(String progID, String server, bool throwOnError)
        {
            throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed");
        }

        internal static Type GetTypeFromCLSIDImpl(Guid clsid, String server, bool throwOnError)
        {
            throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed"); 
        }
#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION

        #endregion

        #region COM
        #endregion
    }

    // this is the introspection only type. This type overrides all the functions with runtime semantics
    // and throws an exception.
    // The idea behind this type is that it relieves RuntimeType from doing honerous checks about ReflectionOnly
    // context.
    // This type should not derive from RuntimeType but it's doing so for convinience.
    // That should not present a security threat though it is risky as a direct call to one of the base method
    // method (RuntimeType) and an instance of this type will work around the reason to have this type in the 
    // first place. However given RuntimeType is not public all its methods are protected and require full trust
    // to be accessed
    [Serializable]
    internal class ReflectionOnlyType : RuntimeType
    {
        private ReflectionOnlyType() { }

        // always throw
        public override RuntimeTypeHandle TypeHandle
        {
            get
            {
                throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
            }
        }
    }

    #region Library
    internal unsafe struct Utf8String
    {
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        private static extern unsafe bool EqualsCaseSensitive(void* szLhs, void* szRhs, int cSz);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private static extern unsafe bool EqualsCaseInsensitive(void* szLhs, void* szRhs, int cSz);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
        [SuppressUnmanagedCodeSecurity]
        private static extern unsafe uint HashCaseInsensitive(void* sz, int cSz);

        private static int GetUtf8StringByteLength(void* pUtf8String)
        {
            int len = 0;

            unsafe
            {
                byte* pItr = (byte*)pUtf8String;

                while (*pItr != 0)
                {
                    len++;
                    pItr++;
                }
            }

            return len;
        }

        private void* m_pStringHeap;        // This is the raw UTF8 string.
        private int m_StringHeapByteLength;

        internal Utf8String(void* pStringHeap)
        {
            m_pStringHeap = pStringHeap;
            if (pStringHeap != null)
            {
                m_StringHeapByteLength = GetUtf8StringByteLength(pStringHeap);
            }
            else
            {
                m_StringHeapByteLength = 0;
            }
        }

        internal unsafe Utf8String(void* pUtf8String, int cUtf8String)
        {
            m_pStringHeap = pUtf8String;
            m_StringHeapByteLength = cUtf8String;
        }

        internal unsafe bool Equals(Utf8String s)
        {
            if (m_pStringHeap == null)
            {
                return s.m_StringHeapByteLength == 0;
            }
            if ((s.m_StringHeapByteLength == m_StringHeapByteLength) && (m_StringHeapByteLength != 0))
            {
                return Utf8String.EqualsCaseSensitive(s.m_pStringHeap, m_pStringHeap, m_StringHeapByteLength);
            }
            return false;
        }

        internal unsafe bool EqualsCaseInsensitive(Utf8String s)
        {
            if (m_pStringHeap == null)
            {
                return s.m_StringHeapByteLength == 0;
            }
            if ((s.m_StringHeapByteLength == m_StringHeapByteLength) && (m_StringHeapByteLength != 0))
            {
                return Utf8String.EqualsCaseInsensitive(s.m_pStringHeap, m_pStringHeap, m_StringHeapByteLength);
            }
            return false;
        }

        internal unsafe uint HashCaseInsensitive()
        {
            return Utf8String.HashCaseInsensitive(m_pStringHeap, m_StringHeapByteLength);
        }

        public override string ToString()
        {
            unsafe
            {
                byte* buf = stackalloc byte[m_StringHeapByteLength];
                byte* pItr = (byte*)m_pStringHeap;

                for (int currentPos = 0; currentPos < m_StringHeapByteLength; currentPos++)
                {
                    buf[currentPos] = *pItr;
                    pItr++;
                }

                if (m_StringHeapByteLength == 0)
                    return "";

                int cResult = Encoding.UTF8.GetCharCount(buf, m_StringHeapByteLength);
                char* result = stackalloc char[cResult];
                Encoding.UTF8.GetChars(buf, m_StringHeapByteLength, result, cResult);
                return new string(result, 0, cResult);
            }
        }
    }
    #endregion
}

namespace System.Reflection
{
    // Reliable hashtable thread safe for multiple readers and single writer. Note that the reliability goes together with thread
    // safety. Thread safety for multiple readers requires atomic update of the state that also makes makes the table
    // reliable in the presence of asynchronous exceptions.
    internal struct CerHashtable<K, V> where K : class
    {
        private class Table
        {
            // Note that m_keys and m_values arrays are immutable to allow lock-free reads. A new instance 
            // of CerHashtable has to be allocated to grow the size of the hashtable.
            internal K[] m_keys;
            internal V[] m_values;
            internal int m_count;

            internal Table(int size)
            {
                size = HashHelpers.GetPrime(size);
                m_keys = new K[size];
                m_values = new V[size];
            }

            internal void Insert(K key, V value)
            {
                int hashcode = GetHashCodeHelper(key);
                if (hashcode < 0)
                    hashcode = ~hashcode;

                K[] keys = m_keys;
                int index = hashcode % keys.Length;

                while (true)
                {
                    K hit = keys[index];

                    if (hit == null)
                    {
                        m_count++;
                        m_values[index] = value;

                        // This volatile write has to be last. It is going to publish the result atomically.
                        //
                        // Note that incrementing the count or setting the value does not do any harm without setting the key. The inconsistency will be ignored 
                        // and it will go away completely during next rehash.
                        Volatile.Write(ref keys[index], key);

                        break;
                    }
                    else
                    {
                        Debug.Assert(!hit.Equals(key), "Key was already in CerHashtable!  Potential race condition (or bug) in the Reflection cache?");

                        index++;
                        if (index >= keys.Length)
                            index -= keys.Length;
                    }
                }
            }
        }

        private Table m_Table;

        private const int MinSize = 7;

        private static int GetHashCodeHelper(K key)
        {
            string sKey = key as string;

            // For strings we don't want the key to differ across domains as CerHashtable might be shared.
            if (sKey == null)
            {
                return key.GetHashCode();
            }
            else
            {
                return sKey.GetLegacyNonRandomizedHashCode();
            }
        }

        private void Rehash(int newSize)
        {
            Table newTable = new Table(newSize);

            Table oldTable = m_Table;
            if (oldTable != null)
            {
                K[] keys = oldTable.m_keys;
                V[] values = oldTable.m_values;

                for (int i = 0; i < keys.Length; i++)
                {
                    K key = keys[i];

                    if (key != null)
                    {
                        newTable.Insert(key, values[i]);
                    }
                }
            }

            // Publish the new table atomically
            Volatile.Write(ref m_Table, newTable);
        }

        internal V this[K key]
        {
            set
            {
                Table table = m_Table;

                if (table != null)
                {
                    int requiredSize = 2 * (table.m_count + 1);
                    if (requiredSize >= table.m_keys.Length)
                        Rehash(requiredSize);
                }
                else
                {
                    Rehash(MinSize);
                }

                m_Table.Insert(key, value);
            }
            get
            {
                Table table = Volatile.Read(ref m_Table);
                if (table == null)
                    return default(V);

                int hashcode = GetHashCodeHelper(key);
                if (hashcode < 0)
                    hashcode = ~hashcode;

                K[] keys = table.m_keys;
                int index = hashcode % keys.Length;

                while (true)
                {
                    // This volatile read has to be first. It is reading the atomically published result.
                    K hit = Volatile.Read(ref keys[index]);

                    if (hit != null)
                    {
                        if (hit.Equals(key))
                            return table.m_values[index];

                        index++;
                        if (index >= keys.Length)
                            index -= keys.Length;
                    }
                    else
                    {
                        return default(V);
                    }
                }
            }
        }
    }
}