summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
blob: 73778d5f27365310d896af8e7da6bc215104eb21 (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
// 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.


// 

namespace System.Reflection.Emit {
    using System;
    using System.Reflection;
    using System.Security;
    using System.Security.Permissions;
    using System.Runtime.InteropServices;
    using System.Runtime.CompilerServices;
    using System.Collections.Generic;
    using CultureInfo = System.Globalization.CultureInfo;
    using System.Threading;
    using System.Runtime.Versioning;
    using System.Diagnostics;
    using System.Diagnostics.Contracts;


    [Serializable]
    [System.Runtime.InteropServices.ComVisible(true)]
    public enum PackingSize
    {
        Unspecified                 = 0,
        Size1                       = 1,
        Size2                       = 2,
        Size4                       = 4,
        Size8                       = 8,
        Size16                      = 16,
        Size32                      = 32,
        Size64                      = 64,
        Size128                     = 128,
    }

    [ClassInterface(ClassInterfaceType.None)]
    [ComDefaultInterface(typeof(_TypeBuilder))]
    [System.Runtime.InteropServices.ComVisible(true)]
    public sealed class TypeBuilder : TypeInfo, _TypeBuilder
    {
        public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
            if(typeInfo==null) return false;            
            return IsAssignableFrom(typeInfo.AsType());
        }

        #region Declarations
        private class CustAttr
        {
            private ConstructorInfo m_con;
            private byte[] m_binaryAttribute;
            private CustomAttributeBuilder m_customBuilder;
            
            public CustAttr(ConstructorInfo con, byte[] binaryAttribute)
            {
                if (con == null)
                    throw new ArgumentNullException(nameof(con));

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

                m_con = con;
                m_binaryAttribute = binaryAttribute;
            }

            public CustAttr(CustomAttributeBuilder customBuilder)
            {
                if (customBuilder == null)
                    throw new ArgumentNullException(nameof(customBuilder));
                Contract.EndContractBlock();

                m_customBuilder = customBuilder;
            }

            public void Bake(ModuleBuilder module, int token)
            {
                if (m_customBuilder == null)
                {
                    TypeBuilder.DefineCustomAttribute(module, token, module.GetConstructorToken(m_con).Token,
                        m_binaryAttribute, false, false);
                }
                else
                {
                    m_customBuilder.CreateCustomAttribute(module, token);
                }
            }
        }
        #endregion
        
        #region Public Static Methods
        public static MethodInfo GetMethod(Type type, MethodInfo method)
        {
            if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));

            // The following checks establishes invariants that more simply put require type to be generic and 
            // method to be a generic method definition declared on the generic type definition of type.
            // To create generic method G<Foo>.M<Bar> these invariants require that G<Foo>.M<S> be created by calling 
            // this function followed by MakeGenericMethod on the resulting MethodInfo to finally get G<Foo>.M<Bar>.
            // We could also allow G<T>.M<Bar> to be created before G<Foo>.M<Bar> (BindGenParm followed by this method) 
            // if we wanted to but that just complicates things so these checks are designed to prevent that scenario.
            
            if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
                throw new ArgumentException(Environment.GetResourceString("Argument_NeedGenericMethodDefinition"), nameof(method));
        
            if (method.DeclaringType == null || !method.DeclaringType.IsGenericTypeDefinition)
                throw new ArgumentException(Environment.GetResourceString("Argument_MethodNeedGenericDeclaringType"), nameof(method));
        
            if (type.GetGenericTypeDefinition() != method.DeclaringType)
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMethodDeclaringType"), nameof(type));
            Contract.EndContractBlock();

            // The following converts from Type or TypeBuilder of G<T> to TypeBuilderInstantiation G<T>. These types
            // both logically represent the same thing. The runtime displays a similar convention by having 
            // G<M>.M() be encoded by a typeSpec whose parent is the typeDef for G<M> and whose instantiation is also G<M>.
            if (type.IsGenericTypeDefinition)
                type = type.MakeGenericType(type.GetGenericArguments());
        
            if (!(type is TypeBuilderInstantiation))
                throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));

            return MethodOnTypeBuilderInstantiation.GetMethod(method, type as TypeBuilderInstantiation);
        }
        public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor)
        {            
            if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));

            if (!constructor.DeclaringType.IsGenericTypeDefinition)
                throw new ArgumentException(Environment.GetResourceString("Argument_ConstructorNeedGenericDeclaringType"), nameof(constructor));
            Contract.EndContractBlock();
        
            if (!(type is TypeBuilderInstantiation))
                throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));

            // TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
            if (type is TypeBuilder && type.IsGenericTypeDefinition)
                type = type.MakeGenericType(type.GetGenericArguments());

            if (type.GetGenericTypeDefinition() != constructor.DeclaringType)
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorDeclaringType"), nameof(type));

            return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, type as TypeBuilderInstantiation);
        }
        public static FieldInfo GetField(Type type, FieldInfo field)
        {
            if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));

            if (!field.DeclaringType.IsGenericTypeDefinition)
                throw new ArgumentException(Environment.GetResourceString("Argument_FieldNeedGenericDeclaringType"), nameof(field));
            Contract.EndContractBlock();
        
            if (!(type is TypeBuilderInstantiation))
                throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));

            // TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
            if (type is TypeBuilder && type.IsGenericTypeDefinition)
                type = type.MakeGenericType(type.GetGenericArguments());

            if (type.GetGenericTypeDefinition() != field.DeclaringType)
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldDeclaringType"), nameof(type));

            return FieldOnTypeBuilderInstantiation.GetField(field, type as TypeBuilderInstantiation);
        }
        #endregion

        #region Public Const
        public const int UnspecifiedTypeSize = 0;
        #endregion

        #region Private Static FCalls
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private static extern void SetParentType(RuntimeModule module, int tdTypeDef, int tkParent);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private static extern void AddInterfaceImpl(RuntimeModule module, int tdTypeDef, int tkInterface);
        #endregion

        #region Internal Static FCalls
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern int DefineMethod(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength, 
            MethodAttributes attributes);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern int DefineMethodSpec(RuntimeModule module, int tkParent, byte[] signature, int sigLength);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern int DefineField(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength, 
            FieldAttributes attributes);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals,  
            byte[] body, int bodyLength,
            byte[] LocalSig, int sigLength, 
            int maxStackSize,
            ExceptionHandler[] exceptions, int numExceptions, 
            int [] tokenFixups, int numTokenFixups);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor, 
            byte[] attr, int attrLength, bool toDisk, bool updateCompilerFlags);

        internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor,
            byte[] attr, bool toDisk, bool updateCompilerFlags)
        {
            byte[] localAttr = null;

            if (attr != null)
            {
                localAttr = new byte[attr.Length];
                Buffer.BlockCopy(attr, 0, localAttr, 0, attr.Length);
            }

            DefineCustomAttribute(module.GetNativeHandle(), tkAssociate, tkConstructor, 
                localAttr, (localAttr != null) ? localAttr.Length : 0, toDisk, updateCompilerFlags);
        }

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern void SetPInvokeData(RuntimeModule module, String DllName, String name, int token, int linkFlags);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern int DefineProperty(RuntimeModule module, int tkParent, String name, PropertyAttributes attributes,
            byte[] signature, int sigLength);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern int DefineEvent(RuntimeModule module, int tkParent, String name, EventAttributes attributes, int tkEventType);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern void DefineMethodSemantics(RuntimeModule module, int tkAssociation, 
            MethodSemanticsAttributes semantics, int tkMethod);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern void DefineMethodImpl(RuntimeModule module, int tkType, int tkBody, int tkDecl);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern void SetMethodImpl(RuntimeModule module, int tkMethod, MethodImplAttributes MethodImplAttributes);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence, 
            ParameterAttributes iParamAttributes, String strParamName);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern int GetTokenFromSig(RuntimeModule module, byte[] signature, int sigLength);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern void SetFieldLayoutOffset(RuntimeModule module, int fdToken, int iOffset);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern void SetClassLayout(RuntimeModule module, int tk, PackingSize iPackingSize, int iTypeSize);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        internal static extern void SetFieldMarshal(RuntimeModule module, int tk, byte[] ubMarshal, int ubSize);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private static extern unsafe void SetConstantValue(RuntimeModule module, int tk, int corType, void* pValue);
        #endregion

        #region Internal\Private Static Members
        private static bool IsPublicComType(Type type)
        {
            // Internal Helper to determine if a type should be added to ComType table.
            // A top level type should be added if it is Public.
            // A nested type should be added if the top most enclosing type is Public 
            //      and all the enclosing types are NestedPublic

            Type enclosingType = type.DeclaringType;
            if (enclosingType != null)
            {
                if (IsPublicComType(enclosingType))
                {
                    if ((type.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic)
                    {
                        return true;
                    }
                }
            }
            else
            {
                if ((type.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public)
                {
                    return true;
                }
            }

            return false;
        }

        [Pure]
        internal static bool IsTypeEqual(Type t1, Type t2)
        {
            // Maybe we are lucky that they are equal in the first place
            if (t1 == t2)
                return true;
            TypeBuilder tb1 = null;
            TypeBuilder tb2 = null;  
            Type runtimeType1 = null;              
            Type runtimeType2 = null;    
            
            // set up the runtimeType and TypeBuilder type corresponding to t1 and t2
            if (t1 is TypeBuilder)
            {
                tb1 =(TypeBuilder)t1;
                // This will be null if it is not baked.
                runtimeType1 = tb1.m_bakedRuntimeType;
            }
            else
            {
                runtimeType1 = t1;
            }

            if (t2 is TypeBuilder)
            {
                tb2 =(TypeBuilder)t2;
                // This will be null if it is not baked.
                runtimeType2 = tb2.m_bakedRuntimeType;
            }
            else
            {
                runtimeType2 = t2;
            }
                
            // If the type builder view is eqaul then it is equal                
            if (tb1 != null && tb2 != null && Object.ReferenceEquals(tb1, tb2))
                return true;

            // if the runtimetype view is eqaul than it is equal                
            if (runtimeType1 != null && runtimeType2 != null && runtimeType1 == runtimeType2)                
                return true;

            return false;                
        }

        internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, Object value)
        {
            // This is a helper function that is used by ParameterBuilder, PropertyBuilder,
            // and FieldBuilder to validate a default value and save it in the meta-data.

            if (value != null)
            {
                Type type = value.GetType();

                // We should allow setting a constant value on a ByRef parameter
                if (destType.IsByRef)
                    destType = destType.GetElementType();

                if (destType.IsEnum)
                {
                    //                                   |  UnderlyingSystemType     |  Enum.GetUnderlyingType() |  IsEnum
                    // ----------------------------------|---------------------------|---------------------------|---------
                    // runtime Enum Type                 |  self                     |  underlying type of enum  |  TRUE
                    // EnumBuilder                       |  underlying type of enum  |  underlying type of enum* |  TRUE
                    // TypeBuilder of enum types**       |  underlying type of enum  |  Exception                |  TRUE
                    // TypeBuilder of enum types (baked) |  runtime enum type        |  Exception                |  TRUE

                    //  *: the behavior of Enum.GetUnderlyingType(EnumBuilder) might change in the future
                    //     so let's not depend on it.
                    // **: created with System.Enum as the parent type.

                    // The above behaviors might not be the most consistent but we have to live with them.

                    Type underlyingType;
                    EnumBuilder enumBldr;
                    TypeBuilder typeBldr;
                    if ((enumBldr = destType as EnumBuilder) != null)
                    {
                        underlyingType = enumBldr.GetEnumUnderlyingType();

                        // The constant value supplied should match either the baked enum type or its underlying type
                        // we don't need to compare it with the EnumBuilder itself because you can never have an object of that type
                        if (type != enumBldr.m_typeBuilder.m_bakedRuntimeType && type != underlyingType)
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                    }
                    else if ((typeBldr = destType as TypeBuilder) != null)
                    {
                        underlyingType = typeBldr.m_enumUnderlyingType;

                        // The constant value supplied should match either the baked enum type or its underlying type
                        // typeBldr.m_enumUnderlyingType is null if the user hasn't created a "value__" field on the enum
                        if (underlyingType == null || (type != typeBldr.UnderlyingSystemType && type != underlyingType))
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                    }
                    else // must be a runtime Enum Type
                    {
                        Debug.Assert(destType is RuntimeType, "destType is not a runtime type, an EnumBuilder, or a TypeBuilder.");

                        underlyingType = Enum.GetUnderlyingType(destType);

                        // The constant value supplied should match either the enum itself or its underlying type
                        if (type != destType && type != underlyingType)
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                    }

                    type = underlyingType;
                }
                else
                {
                    // Note that it is non CLS compliant if destType != type. But RefEmit never guarantees CLS-Compliance.
                    if (!destType.IsAssignableFrom(type))
                        throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
                }
                        
                CorElementType corType = RuntimeTypeHandle.GetCorElementType((RuntimeType)type);

                switch (corType)
                {
                    case CorElementType.I1:
                    case CorElementType.U1:
                    case CorElementType.Boolean:
                    case CorElementType.I2:
                    case CorElementType.U2:
                    case CorElementType.Char:
                    case CorElementType.I4:
                    case CorElementType.U4:
                    case CorElementType.R4:
                    case CorElementType.I8:
                    case CorElementType.U8:
                    case CorElementType.R8:
                        fixed (byte* pData = &JitHelpers.GetPinningHelper(value).m_data)
                            SetConstantValue(module.GetNativeHandle(), tk, (int)corType, pData);
                        break;

                    default:
                        if (type == typeof(String))
                        {
                            fixed (char* pString = (string)value)
                                SetConstantValue(module.GetNativeHandle(), tk, (int)CorElementType.String, pString);
                        }
                        else if (type == typeof(DateTime))
                        {
                            //date is a I8 representation
                            long ticks = ((DateTime)value).Ticks;
                            SetConstantValue(module.GetNativeHandle(), tk, (int)CorElementType.I8, &ticks);
                        }
                        else
                        {
                            throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNotSupported", type.ToString()));
                        }
                        break;
                }
            }
            else
            {
                if (destType.IsValueType)
                {
                    // nullable types can hold null value.
                    if (!(destType.IsGenericType && destType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                        throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNull"));
                }

                SetConstantValue(module.GetNativeHandle(), tk, (int)CorElementType.Class, null);
            }
        }

        #endregion

        #region Private Data Members
        private List<CustAttr> m_ca;
        private TypeToken m_tdType; 
        private ModuleBuilder m_module;
        private String m_strName;
        private String m_strNameSpace;
        private String m_strFullQualName;
        private Type m_typeParent;
        private List<Type> m_typeInterfaces;
        private TypeAttributes m_iAttr;
        private GenericParameterAttributes m_genParamAttributes;
        internal List<MethodBuilder> m_listMethods;
        internal int m_lastTokenizedMethod;
        private int m_constructorCount;
        private int m_iTypeSize;
        private PackingSize m_iPackingSize;
        private TypeBuilder m_DeclaringType;

        // We cannot store this on EnumBuilder because users can define enum types manually using TypeBuilder.
        private Type m_enumUnderlyingType;
        internal bool m_isHiddenGlobalType;
        private bool m_hasBeenCreated;
        private RuntimeType m_bakedRuntimeType;

        private int m_genParamPos;
        private GenericTypeParameterBuilder[] m_inst;
        private bool m_bIsGenParam;
        private MethodBuilder m_declMeth;
        private TypeBuilder m_genTypeDef;
        #endregion

        #region Constructor
        // ctor for the global (module) type
        internal TypeBuilder(ModuleBuilder module)
        {
            m_tdType = new TypeToken((int)MetadataTokenType.TypeDef);
            m_isHiddenGlobalType = true;
            m_module = (ModuleBuilder)module;
            m_listMethods = new List<MethodBuilder>();
            // No token has been created so let's initialize it to -1
            // The first time we call MethodBuilder.GetToken this will incremented.
            m_lastTokenizedMethod = -1;
        }

        // ctor for generic method parameter
        internal TypeBuilder(string szName, int genParamPos, MethodBuilder declMeth)
        {
            Contract.Requires(declMeth != null);
            m_declMeth = declMeth;
            m_DeclaringType =m_declMeth.GetTypeBuilder();
            m_module =declMeth.GetModuleBuilder();
            InitAsGenericParam(szName, genParamPos);
        }

        // ctor for generic type parameter
        private TypeBuilder(string szName, int genParamPos, TypeBuilder declType)
        {
            Contract.Requires(declType != null);
            m_DeclaringType = declType;
            m_module =declType.GetModuleBuilder();
            InitAsGenericParam(szName, genParamPos);
        }

        private void InitAsGenericParam(string szName, int genParamPos)
        {
            m_strName = szName;
            m_genParamPos = genParamPos;
            m_bIsGenParam = true;
            m_typeInterfaces = new List<Type>();
        }

        internal TypeBuilder(
            String name,
            TypeAttributes attr,
            Type parent,
            Type[] interfaces,
            ModuleBuilder module,
            PackingSize iPackingSize,
            int iTypeSize, 
            TypeBuilder enclosingType)
        {
            Init(name, attr, parent, interfaces, module, iPackingSize, iTypeSize, enclosingType);
        }

        private void Init(String fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module,
            PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType)
        {
            if (fullname == null)
                throw new ArgumentNullException(nameof(fullname));

            if (fullname.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fullname));

            if (fullname[0] == '\0')
                throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fullname));


            if (fullname.Length > 1023)
                throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), nameof(fullname));
            Contract.EndContractBlock();

            int i;
            m_module = module;
            m_DeclaringType = enclosingType;
            AssemblyBuilder containingAssem = m_module.ContainingAssemblyBuilder;

            // cannot have two types within the same assembly of the same name
            containingAssem.m_assemblyData.CheckTypeNameConflict(fullname, enclosingType);

            if (enclosingType != null)
            {
                // Nested Type should have nested attribute set.
                // If we are renumbering TypeAttributes' bit, we need to change the logic here.
                if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), nameof(attr));
            }

            int[] interfaceTokens = null;
            if (interfaces != null)
            {
                for(i = 0; i < interfaces.Length; i++)
                {
                    if (interfaces[i] == null)
                    {
                        // cannot contain null in the interface list
                        throw new ArgumentNullException(nameof(interfaces));
                    }
                }
                interfaceTokens = new int[interfaces.Length + 1];
                for(i = 0; i < interfaces.Length; i++)
                {
                    interfaceTokens[i] = m_module.GetTypeTokenInternal(interfaces[i]).Token;
                }
            }

            int iLast = fullname.LastIndexOf('.');
            if (iLast == -1 || iLast == 0)
            {
                // no name space
                m_strNameSpace = String.Empty;
                m_strName = fullname;
            }
            else
            {
                // split the name space
                m_strNameSpace = fullname.Substring(0, iLast);
                m_strName = fullname.Substring(iLast + 1);
            }

            VerifyTypeAttributes(attr);

            m_iAttr = attr;

            SetParent(parent);

            m_listMethods = new List<MethodBuilder>();
            m_lastTokenizedMethod = -1;

            SetInterfaces(interfaces);

            int tkParent = 0;
            if (m_typeParent != null)
                tkParent = m_module.GetTypeTokenInternal(m_typeParent).Token;

            int tkEnclosingType = 0;
            if (enclosingType != null)
            {
                tkEnclosingType = enclosingType.m_tdType.Token;
            }

            m_tdType = new TypeToken(DefineType(m_module.GetNativeHandle(),
                fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens));

            m_iPackingSize = iPackingSize;
            m_iTypeSize = iTypeSize;
            if ((m_iPackingSize != 0) ||(m_iTypeSize != 0))
                SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize);

            m_module.AddType(FullName, this);
        }

        #endregion

        #region Private Members
        private MethodBuilder DefinePInvokeMethodHelper(
            String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
            CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            CheckContext(returnType);
            CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
            CheckContext(parameterTypeRequiredCustomModifiers);
            CheckContext(parameterTypeOptionalCustomModifiers);

            AppDomain.CheckDefinePInvokeSupported();

            lock (SyncRoot)
            {
                return DefinePInvokeMethodHelperNoLock(name, dllName, importName, attributes, callingConvention, 
                                                       returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
                                                       parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
                                                       nativeCallConv, nativeCharSet);
            }
        }

        private MethodBuilder DefinePInvokeMethodHelperNoLock(
            String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
            CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));

            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));

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

            if (dllName.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(dllName));

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

            if (importName.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(importName));

            if ((attributes & MethodAttributes.Abstract) != 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeMethod"));
            Contract.EndContractBlock();

            if ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeOnInterface"));

            ThrowIfCreated();

            attributes = attributes | MethodAttributes.PinvokeImpl;
            MethodBuilder method = new MethodBuilder(name, attributes, callingConvention, 
                returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
                parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
                m_module, this, false);

            //The signature grabbing code has to be up here or the signature won't be finished
            //and our equals check won't work.
            int sigLength;
            byte[] sigBytes = method.GetMethodSignature().InternalGetSignature(out sigLength);

            if (m_listMethods.Contains(method))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_MethodRedefined"));
            }
            m_listMethods.Add(method);

            MethodToken token = method.GetToken();
            
            int linkFlags = 0;
            switch(nativeCallConv)
            {
                case CallingConvention.Winapi:
                    linkFlags =(int)PInvokeMap.CallConvWinapi;
                    break;
                case CallingConvention.Cdecl:
                    linkFlags =(int)PInvokeMap.CallConvCdecl;
                    break;
                case CallingConvention.StdCall:
                    linkFlags =(int)PInvokeMap.CallConvStdcall;
                    break;
                case CallingConvention.ThisCall:
                    linkFlags =(int)PInvokeMap.CallConvThiscall;
                    break;
                case CallingConvention.FastCall:
                    linkFlags =(int)PInvokeMap.CallConvFastcall;
                    break;
            }
            switch(nativeCharSet)
            {
                case CharSet.None:
                    linkFlags |=(int)PInvokeMap.CharSetNotSpec;
                    break;
                case CharSet.Ansi:
                    linkFlags |=(int)PInvokeMap.CharSetAnsi;
                    break;
                case CharSet.Unicode:
                    linkFlags |=(int)PInvokeMap.CharSetUnicode;
                    break;
                case CharSet.Auto:
                    linkFlags |=(int)PInvokeMap.CharSetAuto;
                    break;
            }
            
            SetPInvokeData(m_module.GetNativeHandle(),
                dllName,
                importName,
                token.Token,
                linkFlags);
            method.SetToken(token);

            return method;
        }

        private FieldBuilder DefineDataHelper(String name, byte[] data, int size, FieldAttributes attributes)
        {
            String strValueClassName;
            TypeBuilder valueClassType;
            FieldBuilder fdBuilder;
            TypeAttributes typeAttributes;

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

            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));

            if (size <= 0 || size >= 0x003f0000)
                throw new ArgumentException(Environment.GetResourceString("Argument_BadSizeForData"));
            Contract.EndContractBlock();

            ThrowIfCreated();

            // form the value class name
            strValueClassName = ModuleBuilderData.MULTI_BYTE_VALUE_CLASS + size.ToString();

            // Is this already defined in this module?
            Type temp = m_module.FindTypeBuilderWithName(strValueClassName, false);
            valueClassType = temp as TypeBuilder;

            if (valueClassType == null)
            {
                typeAttributes = TypeAttributes.Public | TypeAttributes.ExplicitLayout | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass;

                // Define the backing value class
                valueClassType = m_module.DefineType(strValueClassName, typeAttributes, typeof(System.ValueType), PackingSize.Size1, size);
                valueClassType.CreateType();
            }

            fdBuilder = DefineField(name, valueClassType,(attributes | FieldAttributes.Static));

            // now we need to set the RVA
            fdBuilder.SetData(data, size);
            return fdBuilder;
        }

        private void VerifyTypeAttributes(TypeAttributes attr)
        {
            // Verify attr consistency for Nesting or otherwise.
            if (DeclaringType == null)
            {
                // Not a nested class.
                if (((attr & TypeAttributes.VisibilityMask) != TypeAttributes.NotPublic) &&((attr & TypeAttributes.VisibilityMask) != TypeAttributes.Public))
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrNestedVisibilityOnNonNestedType"));
                }
            }
            else
            {
                // Nested class.
                if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public))
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrNonNestedVisibilityNestedType"));
                }
            }

            // Verify that the layout mask is valid.
            if (((attr & TypeAttributes.LayoutMask) != TypeAttributes.AutoLayout) &&((attr & TypeAttributes.LayoutMask) != TypeAttributes.SequentialLayout) &&((attr & TypeAttributes.LayoutMask) != TypeAttributes.ExplicitLayout))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrInvalidLayout"));
            }

            // Check if the user attempted to set any reserved bits.
            if ((attr & TypeAttributes.ReservedMask) != 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrReservedBitsSet"));
            }
        }

        [Pure]
        public bool IsCreated()
        { 
            return m_hasBeenCreated;
        }
        
        #endregion

        #region FCalls
        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private extern static int DefineType(RuntimeModule module,
            String fullname, int tkParent, TypeAttributes attributes, int tkEnclosingType, int[] interfaceTokens);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private extern static int DefineGenericParam(RuntimeModule module,
            String name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints);

        [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
		[SuppressUnmanagedCodeSecurity]
        private static extern void TermCreateClass(RuntimeModule module, int tk, ObjectHandleOnStack type);
        #endregion

        #region Internal Methods
        internal void ThrowIfCreated()
        {
            if (IsCreated())
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
        }

        internal object SyncRoot
        {
            get
            {
                return m_module.SyncRoot;
            }
        }

        internal ModuleBuilder GetModuleBuilder()
        {
            return m_module;
        }

        internal RuntimeType BakedRuntimeType
        {
            get
            {
                return m_bakedRuntimeType;
            }
        }

        internal void SetGenParamAttributes(GenericParameterAttributes genericParameterAttributes)
        {
            m_genParamAttributes = genericParameterAttributes;
        }
        
        internal void SetGenParamCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
        {
            CustAttr ca = new CustAttr(con, binaryAttribute);

            lock(SyncRoot)
            {
                SetGenParamCustomAttributeNoLock(ca);
            }
        }

        internal void SetGenParamCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            CustAttr ca = new CustAttr(customBuilder);

            lock(SyncRoot)
            {
                SetGenParamCustomAttributeNoLock(ca);
            }
        }

        private void SetGenParamCustomAttributeNoLock(CustAttr ca)
        {
            if (m_ca == null)
                m_ca = new List<TypeBuilder.CustAttr>();
        
            m_ca.Add(ca);
        }
        #endregion

        #region Object Overrides
        public override String ToString()
        {
                return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
        }

        #endregion

        #region MemberInfo Overrides
        public override Type DeclaringType 
        {
            get { return m_DeclaringType; }
        }

        public override Type ReflectedType 
        {
            // Return the class that was used to obtain this field.
            
            get { return m_DeclaringType; }
        }

        public override String Name 
        {
            get { return m_strName; }
        }

        public override Module Module 
        {
            get { return GetModuleBuilder(); }
        }

        internal int MetadataTokenInternal
        {
            get { return m_tdType.Token; }
        }

        #endregion

        #region Type Overrides
        public override Guid GUID 
        {
            get 
            {
                if (!IsCreated())
                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
                Contract.EndContractBlock();

                return m_bakedRuntimeType.GUID;
            }
        }

        public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target,
            Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
        }

        public override Assembly Assembly 
        {
            get { return m_module.Assembly; }
        }

        public override RuntimeTypeHandle TypeHandle 
        {
             
            get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
        }

        public override String FullName 
        {
            get 
            { 
                if (m_strFullQualName == null)
                    m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);

                return m_strFullQualName;
            }
        }

        public override String Namespace 
        {
            get { return m_strNameSpace; }
        }

        public override String AssemblyQualifiedName 
        {
            get 
            {                
                return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
            }
        }

        public override Type BaseType 
        {
            get{ return m_typeParent; }
        }

        protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
                CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers);
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetConstructors(bindingAttr);
        }

        protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
                CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            if (types == null)
            {
                return m_bakedRuntimeType.GetMethod(name, bindingAttr);
            }
            else
            {
                return m_bakedRuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
            }
        }

        public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetMethods(bindingAttr);
        }

        public override FieldInfo GetField(String name, BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetField(name, bindingAttr);
        }

        public override FieldInfo[] GetFields(BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetFields(bindingAttr);
        }

        public override Type GetInterface(String name,bool ignoreCase)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();
            
            return m_bakedRuntimeType.GetInterface(name, ignoreCase);
        }

        public override Type[] GetInterfaces()
        {
            if (m_bakedRuntimeType != null)
            {
                return m_bakedRuntimeType.GetInterfaces();
            }

            if (m_typeInterfaces == null)
            {
                return EmptyArray<Type>.Value;
            }

            return m_typeInterfaces.ToArray();
        }

        public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetEvent(name, bindingAttr);
        }

        public override EventInfo[] GetEvents()
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetEvents();
        }

        protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
                Type returnType, Type[] types, ParameterModifier[] modifiers)
        {
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
        }

        public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetProperties(bindingAttr);
        }

        public override Type[] GetNestedTypes(BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetNestedTypes(bindingAttr);
        }

        public override Type GetNestedType(String name, BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetNestedType(name,bindingAttr);
        }

        public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetMember(name, type, bindingAttr);
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        public override InterfaceMapping GetInterfaceMap(Type interfaceType)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetInterfaceMap(interfaceType);
        }

        public override EventInfo[] GetEvents(BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetEvents(bindingAttr);
        }

        public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return m_bakedRuntimeType.GetMembers(bindingAttr);
        }
        
        public override bool IsAssignableFrom(Type c)
        {
            if (TypeBuilder.IsTypeEqual(c, this))
                return true;
        
            Type fromRuntimeType = null;
            TypeBuilder fromTypeBuilder = c as TypeBuilder;
            
            if (fromTypeBuilder != null)
                fromRuntimeType = fromTypeBuilder.m_bakedRuntimeType;
            else
                fromRuntimeType = c;
                
            if (fromRuntimeType != null && fromRuntimeType is RuntimeType)
            {
                // fromType is baked. So if this type is not baked, it cannot be assignable to!
                if (m_bakedRuntimeType == null)
                    return false;
                    
                // since toType is also baked, delegate to the base
                return m_bakedRuntimeType.IsAssignableFrom(fromRuntimeType);
            }
            
            // So if c is not a runtimeType nor TypeBuilder. We don't know how to deal with it. 
            // return false then.
            if (fromTypeBuilder == null)
                return false;
                                 
            // If fromTypeBuilder is a subclass of this class, then c can be cast to this type.
            if (fromTypeBuilder.IsSubclassOf(this))
                return true;
                
            if (this.IsInterface == false)
                return false;
                                                                                  
            // now is This type a base type on one of the interface impl?
            Type[] interfaces = fromTypeBuilder.GetInterfaces();
            for(int i = 0; i < interfaces.Length; i++)
            {
                // unfortunately, IsSubclassOf does not cover the case when they are the same type.
                if (TypeBuilder.IsTypeEqual(interfaces[i], this))
                    return true;
            
                if (interfaces[i].IsSubclassOf(this))
                    return true;
            }
            return false;                                                                               
        }        

        protected override TypeAttributes GetAttributeFlagsImpl()
        {
            return m_iAttr;
        }

        protected override bool IsArrayImpl()
        {
            return false;
        }
        protected override bool IsByRefImpl()
        {
            return false;
        }
        protected override bool IsPointerImpl()
        {
            return false;
        }
        protected override bool IsPrimitiveImpl()
        {
            return false;
        }

        protected override bool IsCOMObjectImpl()
        {
            return((GetAttributeFlagsImpl() & TypeAttributes.Import) != 0) ? true : false;
        }

        public override Type GetElementType()
        {
            
            // You will never have to deal with a TypeBuilder if you are just referring to arrays.
            throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
        }

        protected override bool HasElementTypeImpl()
        {
            return false;
        }

        public override bool IsSecurityCritical
        {
            get { return true; }
        }

        public override bool IsSecuritySafeCritical
        {
            get { return false; }
        }

        public override bool IsSecurityTransparent
        {
            get { return false; }
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        [Pure]
        public override bool IsSubclassOf(Type c)
        {
            Type p = this;

            if (TypeBuilder.IsTypeEqual(p, c))
                return false;

            p = p.BaseType; 
               
            while(p != null) 
            {
                if (TypeBuilder.IsTypeEqual(p, c))
                    return true;

                p = p.BaseType;
            }

            return false;
        }
        
        public override Type UnderlyingSystemType 
        {
            get 
            {
                if (m_bakedRuntimeType != null)
                    return m_bakedRuntimeType;

                if (IsEnum)
                {
                    if (m_enumUnderlyingType == null)
                        throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoUnderlyingTypeOnEnum"));
                    
                    return m_enumUnderlyingType;                       
                }
                else
                {
                    return this;
                }
            }
        }

        public override Type MakePointerType() 
        { 
            return SymbolType.FormCompoundType("*", this, 0); 
        }

        public override Type MakeByRefType() 
        {
            return SymbolType.FormCompoundType("&", this, 0);
        }

        public override Type MakeArrayType() 
        {
            return SymbolType.FormCompoundType("[]", this, 0);
        }

        public override Type MakeArrayType(int rank) 
        {
            if (rank <= 0)
                throw new IndexOutOfRangeException();
            Contract.EndContractBlock();

            string szrank = "";
            if (rank == 1)
            {
                szrank = "*";
            }
            else 
            {
                for(int i = 1; i < rank; i++)
                    szrank += ",";
            }

            string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
            return SymbolType.FormCompoundType(s, this, 0);
        }

        #endregion

        #region ICustomAttributeProvider Implementation
        public override Object[] GetCustomAttributes(bool inherit)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
            Contract.EndContractBlock();

            return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit);
        }

        public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));

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

            RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;

            if (attributeRuntimeType == null)
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));

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

        public override bool IsDefined(Type attributeType, bool inherit)
        {
            if (!IsCreated())
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));

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

            RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;

            if (attributeRuntimeType == null)
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));

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

        #endregion

        #region Public Member
        
        #region DefineType
        public override GenericParameterAttributes GenericParameterAttributes { get { return m_genParamAttributes; } }

        internal void SetInterfaces(params Type[] interfaces) 
        { 
            ThrowIfCreated();

            m_typeInterfaces = new List<Type>();
            if (interfaces != null)
            {
                m_typeInterfaces.AddRange(interfaces);
            }
        }


        public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
        {
            if (names == null)
                throw new ArgumentNullException(nameof(names));

            if (names.Length == 0)
                throw new ArgumentException();
            Contract.EndContractBlock();
           
            for (int i = 0; i < names.Length; i ++)
                if (names[i] == null)
                    throw new ArgumentNullException(nameof(names));

            if (m_inst != null)
                throw new InvalidOperationException();

            m_inst = new GenericTypeParameterBuilder[names.Length];
            for(int i = 0; i < names.Length; i ++)
                m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));

            return m_inst;
        }

		
		public override Type MakeGenericType(params Type[] typeArguments)
		{
            CheckContext(typeArguments);
        
            return TypeBuilderInstantiation.MakeGenericType(this, typeArguments); 
        }
		
        public override Type[] GetGenericArguments() { return m_inst; }
        // If a TypeBuilder is generic, it must be a generic type definition
        // All instantiated generic types are TypeBuilderInstantiation.
        public override bool IsGenericTypeDefinition { get { return IsGenericType; } }
       	public override bool IsGenericType { get { return m_inst != null; } }
        public override bool IsGenericParameter { get { return m_bIsGenParam; } }
        public override bool IsConstructedGenericType { get { return false; } }

        public override int GenericParameterPosition { get { return m_genParamPos; } }
        public override MethodBase DeclaringMethod { get { return m_declMeth; } }
        public override Type GetGenericTypeDefinition() { if (IsGenericTypeDefinition) return this; if (m_genTypeDef == null) throw new InvalidOperationException(); return m_genTypeDef; }
        #endregion

        #region Define Method
        public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
        {
            lock(SyncRoot)
            {
                DefineMethodOverrideNoLock(methodInfoBody, methodInfoDeclaration);
            }
        }

        private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
        {
            if (methodInfoBody == null)
                throw new ArgumentNullException(nameof(methodInfoBody));

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

            ThrowIfCreated();
                                                                
            if (!object.ReferenceEquals(methodInfoBody.DeclaringType, this))
                // Loader restriction: body method has to be from this class
                throw new ArgumentException(Environment.GetResourceString("ArgumentException_BadMethodImplBody"));
            
            MethodToken     tkBody;
            MethodToken     tkDecl;

            tkBody = m_module.GetMethodTokenInternal(methodInfoBody);
            tkDecl = m_module.GetMethodTokenInternal(methodInfoDeclaration);

            DefineMethodImpl(m_module.GetNativeHandle(), m_tdType.Token, tkBody.Token, tkDecl.Token);
        }

        public MethodBuilder DefineMethod(String name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            return DefineMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
        }

        public MethodBuilder DefineMethod(String name, MethodAttributes attributes)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            return DefineMethod(name, attributes, CallingConventions.Standard, null, null);
        }

        public MethodBuilder DefineMethod(String name, MethodAttributes attributes, CallingConventions callingConvention)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            return DefineMethod(name, attributes, callingConvention, null, null);
        }

        public MethodBuilder DefineMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
            Type returnType, Type[] parameterTypes)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            return DefineMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
        }
        
        public MethodBuilder DefineMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
        {
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);

            lock(SyncRoot)
            {
                return DefineMethodNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, 
                                          returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, 
                                          parameterTypeOptionalCustomModifiers);
            }
        }
            
        private MethodBuilder DefineMethodNoLock(String name, MethodAttributes attributes, CallingConventions callingConvention,
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));

            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
            Contract.Ensures(Contract.Result<MethodBuilder>() != null);
            Contract.EndContractBlock();

            CheckContext(returnType);
            CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
            CheckContext(parameterTypeRequiredCustomModifiers);
            CheckContext(parameterTypeOptionalCustomModifiers);

            if (parameterTypes != null)
            {
                if (parameterTypeOptionalCustomModifiers != null && parameterTypeOptionalCustomModifiers.Length != parameterTypes.Length)
                    throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeOptionalCustomModifiers), nameof(parameterTypes)));

                if (parameterTypeRequiredCustomModifiers != null && parameterTypeRequiredCustomModifiers.Length != parameterTypes.Length)
                    throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeRequiredCustomModifiers), nameof(parameterTypes)));
            }

            ThrowIfCreated();

            if (!m_isHiddenGlobalType)
            {
                if (((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) &&
                   (attributes & MethodAttributes.Abstract) == 0 &&(attributes & MethodAttributes.Static) == 0)
                    throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod"));               
            }

            // pass in Method attributes
            MethodBuilder method = new MethodBuilder(
                name, attributes, callingConvention, 
                returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
                parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, 
                m_module, this, false);

            if (!m_isHiddenGlobalType)
            {
                //If this method is declared to be a constructor, increment our constructor count.
                if ((method.Attributes & MethodAttributes.SpecialName) != 0 && method.Name.Equals(ConstructorInfo.ConstructorName)) 
                {
                    m_constructorCount++;
                }
            }

            m_listMethods.Add(method);

            return method;
        }

        #endregion

        #region Define Constructor
        [System.Runtime.InteropServices.ComVisible(true)]
        public ConstructorBuilder DefineTypeInitializer()
        {
            lock(SyncRoot)
            {
                return DefineTypeInitializerNoLock();
            }
        }

        private ConstructorBuilder DefineTypeInitializerNoLock()
        {
            ThrowIfCreated();

            // change the attributes and the class constructor's name
            MethodAttributes attr = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName;

            ConstructorBuilder constBuilder = new ConstructorBuilder(
                ConstructorInfo.TypeConstructorName, attr, CallingConventions.Standard, null, m_module, this);

            return constBuilder;
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes)
        {
            if ((m_iAttr & TypeAttributes.Interface) == TypeAttributes.Interface)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ConstructorNotAllowedOnInterface"));
            }

            lock(SyncRoot)
            {
                return DefineDefaultConstructorNoLock(attributes);
            }
        }

        private ConstructorBuilder DefineDefaultConstructorNoLock(MethodAttributes attributes)
        {
            ConstructorBuilder constBuilder;

            // get the parent class's default constructor
            // We really don't want(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic) here.  We really want
            // constructors visible from the subclass, but that is not currently
            // available in BindingFlags.  This more open binding is open to
            // runtime binding failures(like if we resolve to a private
            // constructor).
            ConstructorInfo con = null;

            if (m_typeParent is TypeBuilderInstantiation)
            {
                Type genericTypeDefinition = m_typeParent.GetGenericTypeDefinition();

                if (genericTypeDefinition is TypeBuilder)
                    genericTypeDefinition = ((TypeBuilder)genericTypeDefinition).m_bakedRuntimeType;

                if (genericTypeDefinition == null)
                    throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));

                Type inst = genericTypeDefinition.MakeGenericType(m_typeParent.GetGenericArguments());

                if (inst is TypeBuilderInstantiation)
                    con = TypeBuilder.GetConstructor(inst, genericTypeDefinition.GetConstructor(
                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null));
                else                
                    con = inst.GetConstructor(
                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
            }

            if (con == null)
            {
                con = m_typeParent.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
            }

            if (con == null)
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_NoParentDefaultConstructor"));

            // Define the constructor Builder
            constBuilder = DefineConstructor(attributes, CallingConventions.Standard, null);
            m_constructorCount++;

            // generate the code to call the parent's default constructor
            ILGenerator il = constBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call,con);
            il.Emit(OpCodes.Ret);

            constBuilder.m_isDefaultConstructor = true;
            return constBuilder;
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
        {
            return DefineConstructor(attributes, callingConvention, parameterTypes, null, null);
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, 
            Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
        {
            if ((m_iAttr & TypeAttributes.Interface) == TypeAttributes.Interface && (attributes & MethodAttributes.Static) != MethodAttributes.Static)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ConstructorNotAllowedOnInterface"));
            }

            lock(SyncRoot)
            {
                return DefineConstructorNoLock(attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
            }
        }

        private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention, 
            Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
        {
            CheckContext(parameterTypes);
            CheckContext(requiredCustomModifiers);
            CheckContext(optionalCustomModifiers);

            ThrowIfCreated();

            String name;

            if ((attributes & MethodAttributes.Static) == 0)
            {
                name = ConstructorInfo.ConstructorName;
            }
            else
            {
                name = ConstructorInfo.TypeConstructorName;
            }

            attributes = attributes | MethodAttributes.SpecialName;

            ConstructorBuilder constBuilder = 
                new ConstructorBuilder(name, attributes, callingConvention, 
                    parameterTypes, requiredCustomModifiers, optionalCustomModifiers, m_module, this);

            m_constructorCount++;

            return constBuilder;
        }

        #endregion

        #region Define PInvoke
        public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes,
            CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
            CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            MethodBuilder method = DefinePInvokeMethodHelper(
                name, dllName, name, attributes, callingConvention, returnType, null, null, 
                parameterTypes, null, null, nativeCallConv, nativeCharSet);
            return method;
        }

        public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, 
            CallingConventions callingConvention, Type returnType, Type[] parameterTypes, 
            CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            MethodBuilder method = DefinePInvokeMethodHelper(
                name, dllName, entryName, attributes, callingConvention, returnType, null, null, 
                parameterTypes, null, null, nativeCallConv, nativeCharSet);
            return method;
        }

        public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes,
            CallingConventions callingConvention, 
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
            CallingConvention nativeCallConv, CharSet nativeCharSet)
        {
            MethodBuilder method = DefinePInvokeMethodHelper(
            name, dllName, entryName, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, 
            parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, nativeCallConv, nativeCharSet);
            return method;
        }

        #endregion

        #region Define Nested Type
        public TypeBuilder DefineNestedType(String name)
        {
            lock(SyncRoot)
            {
                return DefineNestedTypeNoLock(name, TypeAttributes.NestedPrivate, null, null, PackingSize.Unspecified, UnspecifiedTypeSize);
            }
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
        {
            lock(SyncRoot)
            {
                // Why do we only call CheckContext here? Why don't we call it in the other overloads?
                CheckContext(parent);
                CheckContext(interfaces);

                return DefineNestedTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, UnspecifiedTypeSize);
            }
        }

        public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent)
        {
            lock(SyncRoot)
            {
                return DefineNestedTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, UnspecifiedTypeSize);
            }
        }

        public TypeBuilder DefineNestedType(String name, TypeAttributes attr)
        {
            lock(SyncRoot)
            {
                return DefineNestedTypeNoLock(name, attr, null, null, PackingSize.Unspecified, UnspecifiedTypeSize);
            }
        }

        public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, int typeSize)
        {
            lock(SyncRoot)
            {
                return DefineNestedTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typeSize);
            }
        }

        public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize)
        {
            lock(SyncRoot)
            {
                return DefineNestedTypeNoLock(name, attr, parent, null, packSize, UnspecifiedTypeSize);
            }
        }

        public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize, int typeSize)
        {
            lock (SyncRoot)
            {
                return DefineNestedTypeNoLock(name, attr, parent, null, packSize, typeSize);
            }
        }

        private TypeBuilder DefineNestedTypeNoLock(String name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packSize, int typeSize)
        {
            return new TypeBuilder(name, attr, parent, interfaces, m_module, packSize, typeSize, this);
        }

        #endregion

        #region Define Field
        public FieldBuilder DefineField(String fieldName, Type type, FieldAttributes attributes) 
        {
            return DefineField(fieldName, type, null, null, attributes);
        }

        public FieldBuilder DefineField(String fieldName, Type type, Type[] requiredCustomModifiers, 
            Type[] optionalCustomModifiers, FieldAttributes attributes) 
        {
            lock(SyncRoot)
            {
                return DefineFieldNoLock(fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes);
            }
        }

        private FieldBuilder DefineFieldNoLock(String fieldName, Type type, Type[] requiredCustomModifiers, 
            Type[] optionalCustomModifiers, FieldAttributes attributes) 
        {
            ThrowIfCreated();
            CheckContext(type);
            CheckContext(requiredCustomModifiers);

            if (m_enumUnderlyingType == null && IsEnum == true)
            {
                if ((attributes & FieldAttributes.Static) == 0)
                {
                    // remember the underlying type for enum type
                    m_enumUnderlyingType = type;
                }                   
            }

            return new FieldBuilder(this, fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes);
        }

        public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
        {
            lock(SyncRoot)
            {
                return DefineInitializedDataNoLock(name, data, attributes);
            }
        }

        private FieldBuilder DefineInitializedDataNoLock(String name, byte[] data, FieldAttributes attributes)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            Contract.EndContractBlock();

            // This method will define an initialized Data in .sdata.
            // We will create a fake TypeDef to represent the data with size. This TypeDef
            // will be the signature for the Field.

            return DefineDataHelper(name, data, data.Length, attributes);
        }

        public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
        {
            lock(SyncRoot)
            {
                return DefineUninitializedDataNoLock(name, size, attributes);
            }
        }

        private FieldBuilder DefineUninitializedDataNoLock(String name, int size, FieldAttributes attributes)
        {
            // This method will define an uninitialized Data in .sdata.
            // We will create a fake TypeDef to represent the data with size. This TypeDef
            // will be the signature for the Field.
            return DefineDataHelper(name, null, size, attributes);
        }

        #endregion

        #region Define Properties and Events
        public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
        {
            return DefineProperty(name, attributes, returnType, null, null, parameterTypes, null, null); 
        }

        public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, 
            CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
        {
            return DefineProperty(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); 
        }


        public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, 
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, 
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
        {
            return DefineProperty(name, attributes, (CallingConventions)0, returnType, 
                returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, 
                parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); 
        }

        public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, CallingConventions callingConvention, 
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, 
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
        {
            lock(SyncRoot)
            {
                return DefinePropertyNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, 
                                            parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
            }
        }

        private PropertyBuilder DefinePropertyNoLock(String name, PropertyAttributes attributes, CallingConventions callingConvention,
            Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, 
            Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
            Contract.EndContractBlock();

            CheckContext(returnType);
            CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
            CheckContext(parameterTypeRequiredCustomModifiers);
            CheckContext(parameterTypeOptionalCustomModifiers);

            SignatureHelper sigHelper;
            int         sigLength;
            byte[]      sigBytes;

            ThrowIfCreated();

            // get the signature in SignatureHelper form
            sigHelper = SignatureHelper.GetPropertySigHelper(
                m_module, callingConvention,
                returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
                parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);

            // get the signature in byte form
            sigBytes = sigHelper.InternalGetSignature(out sigLength);

            PropertyToken prToken = new PropertyToken(DefineProperty(
                m_module.GetNativeHandle(),
                m_tdType.Token,
                name,
                attributes,
                sigBytes,
                sigLength));

            // create the property builder now.
            return new PropertyBuilder(
                    m_module,
                    name,
                    sigHelper,
                    attributes,
                    returnType,
                    prToken,
                    this);
        }

        public EventBuilder DefineEvent(String name, EventAttributes attributes, Type eventtype)
        {
            lock(SyncRoot)
            {
                return DefineEventNoLock(name, attributes, eventtype);
            }
        }

        private EventBuilder DefineEventNoLock(String name, EventAttributes attributes, Type eventtype)
        {
            if (name == null)
                throw new ArgumentNullException(nameof(name));
            if (name.Length == 0)
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
            if (name[0] == '\0')
                throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name));
            Contract.EndContractBlock();

            int tkType;
            EventToken      evToken;
            
            CheckContext(eventtype);

            ThrowIfCreated();

            tkType = m_module.GetTypeTokenInternal( eventtype ).Token;

            // Internal helpers to define property records
            evToken = new EventToken(DefineEvent(
                m_module.GetNativeHandle(),
                m_tdType.Token,
                name,
                attributes,
                tkType));

            // create the property builder now.
            return new EventBuilder(
                    m_module,
                    name,
                    attributes,
                    //tkType,
                    this,
                    evToken);
        }

        #endregion

        #region Create Type

        public TypeInfo CreateTypeInfo()
        {
            lock (SyncRoot)
            {
                return CreateTypeNoLock();
            }
        }

        public Type CreateType()
        {
            lock (SyncRoot)
            {
                return CreateTypeNoLock();
            }
        }

        internal void CheckContext(params Type[][] typess)
        {
            m_module.CheckContext(typess);            
        }
        internal void CheckContext(params Type[] types)
        {
            m_module.CheckContext(types);
        }

        private TypeInfo CreateTypeNoLock()
        {
            if (IsCreated())
                return m_bakedRuntimeType;

            ThrowIfCreated();

            if (m_typeInterfaces == null)
                m_typeInterfaces = new List<Type>();

            int[] interfaceTokens = new int[m_typeInterfaces.Count];
            for(int i = 0; i < m_typeInterfaces.Count; i++)
            {
                interfaceTokens[i] = m_module.GetTypeTokenInternal(m_typeInterfaces[i]).Token;
            }

            int tkParent = 0;
            if (m_typeParent != null)
                tkParent = m_module.GetTypeTokenInternal(m_typeParent).Token;

            if (IsGenericParameter)
            {
                int[] constraints; // Array of token constrains terminated by null token

                if (m_typeParent != null)
                {
                    constraints = new int[m_typeInterfaces.Count + 2];
                    constraints[constraints.Length - 2] = tkParent;
                }
                else
                {
                    constraints = new int[m_typeInterfaces.Count + 1];
                }

                for (int i = 0; i < m_typeInterfaces.Count; i++)
                {
                    constraints[i] = m_module.GetTypeTokenInternal(m_typeInterfaces[i]).Token;
                }

                int declMember = m_declMeth == null ? m_DeclaringType.m_tdType.Token : m_declMeth.GetToken().Token;
                m_tdType = new TypeToken(DefineGenericParam(m_module.GetNativeHandle(),
                    m_strName, declMember, m_genParamAttributes, m_genParamPos, constraints));

                if (m_ca != null)
                {
                    foreach (CustAttr ca in m_ca)
                        ca.Bake(m_module, MetadataTokenInternal);
                }

                m_hasBeenCreated = true;

                // Baking a generic parameter does not put sufficient information into the metadata to actually be able to load it as a type,
                // the associated generic type/method needs to be baked first. So we return this rather than the baked type.
                return this;
            }
            else
            {
                // Check for global typebuilder
                if (((m_tdType.Token & 0x00FFFFFF) != 0) && ((tkParent & 0x00FFFFFF) != 0))
                    SetParentType(m_module.GetNativeHandle(), m_tdType.Token, tkParent);
            
                if (m_inst != null)
                    foreach (Type tb in m_inst)
                        if (tb is GenericTypeParameterBuilder)
                            ((GenericTypeParameterBuilder)tb).m_type.CreateType();
            }

            byte [] body;
            MethodAttributes methodAttrs;
                            
            if (!m_isHiddenGlobalType)
            {
                // create a public default constructor if this class has no constructor.
                // except if the type is Interface, ValueType, Enum, or a static class.
                if (m_constructorCount == 0 && ((m_iAttr & TypeAttributes.Interface) == 0) && !IsValueType && ((m_iAttr & (TypeAttributes.Abstract | TypeAttributes.Sealed)) != (TypeAttributes.Abstract | TypeAttributes.Sealed)))
                {
                    DefineDefaultConstructor(MethodAttributes.Public);
                }
            }

            int size = m_listMethods.Count;

            for(int i = 0; i < size; i++)
            {
                MethodBuilder meth = m_listMethods[i];


                if (meth.IsGenericMethodDefinition)
                    meth.GetToken(); // Doubles as "CreateMethod" for MethodBuilder -- analagous to CreateType()

                methodAttrs = meth.Attributes;

                // Any of these flags in the implemenation flags is set, we will not attach the IL method body
                if (((meth.GetMethodImplementationFlags() &(MethodImplAttributes.CodeTypeMask|MethodImplAttributes.PreserveSig|MethodImplAttributes.Unmanaged)) != MethodImplAttributes.IL) ||
                    ((methodAttrs & MethodAttributes.PinvokeImpl) !=(MethodAttributes) 0))
                {
                    continue;
                }

                int sigLength;
                byte[] localSig = meth.GetLocalSignature(out sigLength);
                 
                // Check that they haven't declared an abstract method on a non-abstract class
                if (((methodAttrs & MethodAttributes.Abstract) != 0) &&((m_iAttr & TypeAttributes.Abstract) == 0))
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadTypeAttributesNotAbstract"));
                }

                body = meth.GetBody();

                // If this is an abstract method or an interface, we don't need to set the IL.

                if ((methodAttrs & MethodAttributes.Abstract) != 0)
                {
                    // We won't check on Interface because we can have class static initializer on interface.
                    // We will just let EE or validator to catch the problem.

                    //((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface))

                    if (body != null)
                        throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadMethodBody"));
                }
                else if (body == null || body.Length == 0)
                {
                    // If it's not an abstract or an interface, set the IL.
                    if (meth.m_ilGenerator != null)
                    {
                        // we need to bake the method here.
                        meth.CreateMethodBodyHelper(meth.GetILGenerator());
                    }

                    body = meth.GetBody();

                    if ((body == null || body.Length == 0) && !meth.m_canBeRuntimeImpl)
                        throw new InvalidOperationException(
                            Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", meth.Name) ); 
                }

                int maxStack = meth.GetMaxStack();

                ExceptionHandler[] exceptions = meth.GetExceptionHandlers();
                int[] tokenFixups = meth.GetTokenFixups();

                SetMethodIL(m_module.GetNativeHandle(), meth.GetToken().Token, meth.InitLocals, 
                    body, (body != null) ? body.Length : 0,
                    localSig, sigLength, maxStack,
                    exceptions, (exceptions != null) ? exceptions.Length : 0,
                    tokenFixups, (tokenFixups != null) ? tokenFixups.Length : 0);

                if (m_module.ContainingAssemblyBuilder.m_assemblyData.m_access == AssemblyBuilderAccess.Run)
                {
                    // if we don't need the data structures to build the method any more
                    // throw them away.
                    meth.ReleaseBakedStructures();
                }
            }

            m_hasBeenCreated = true;

            // Terminate the process.
            RuntimeType cls = null;
            TermCreateClass(m_module.GetNativeHandle(), m_tdType.Token, JitHelpers.GetObjectHandleOnStack(ref cls));

            if (!m_isHiddenGlobalType)
            {
                m_bakedRuntimeType = cls;

                // if this type is a nested type, we need to invalidate the cached nested runtime type on the nesting type
                if (m_DeclaringType != null && m_DeclaringType.m_bakedRuntimeType != null)
                {
                   m_DeclaringType.m_bakedRuntimeType.InvalidateCachedNestedType();
                }

                return cls;
            }
            else
            {
                return null;
            }
        }

        #endregion

        #region Misc
        public int Size
        {
            get { return m_iTypeSize; }
        }
        
        public PackingSize PackingSize 
        {
            get { return m_iPackingSize; }
        }

        public void SetParent(Type parent)
        {
            ThrowIfCreated();

            if (parent != null)
            {
                CheckContext(parent);

                if (parent.IsInterface)
                    throw new ArgumentException(Environment.GetResourceString("Argument_CannotSetParentToInterface"));

                m_typeParent = parent;
            }
            else
            {
                if ((m_iAttr & TypeAttributes.Interface) != TypeAttributes.Interface)
                {
                    m_typeParent = typeof(Object);
                }
                else
                {
                    if ((m_iAttr & TypeAttributes.Abstract) == 0)
                        throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadInterfaceNotAbstract"));

                    // there is no extends for interface class
                    m_typeParent = null;
                }
            }
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        public void AddInterfaceImplementation(Type interfaceType)
        {
            if (interfaceType == null)
            {
                throw new ArgumentNullException(nameof(interfaceType));
            }
            Contract.EndContractBlock();

            CheckContext(interfaceType);
            
            ThrowIfCreated();

            TypeToken tkInterface = m_module.GetTypeTokenInternal(interfaceType);
            AddInterfaceImpl(m_module.GetNativeHandle(), m_tdType.Token, tkInterface.Token);

            m_typeInterfaces.Add(interfaceType);
        }

public TypeToken TypeToken 
        {
            get 
            {
                if (IsGenericParameter)
                    ThrowIfCreated();

                return m_tdType; 
            }
        }


        [System.Runtime.InteropServices.ComVisible(true)]
        public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
        {
            if (con == null)
                throw new ArgumentNullException(nameof(con));

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

            TypeBuilder.DefineCustomAttribute(m_module, m_tdType.Token, ((ModuleBuilder)m_module).GetConstructorToken(con).Token,
                binaryAttribute, false, false);
        }

        public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
        {
            if (customBuilder == null)
                throw new ArgumentNullException(nameof(customBuilder));
            Contract.EndContractBlock();

            customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, m_tdType.Token);
        }

        #endregion

        #endregion
    }
}