3 // TypeBuilderTest.cs - NUnit Test Cases for the TypeBuilder class
5 // Zoltan Varga (vargaz@freemail.hu)
7 // (C) Ximian, Inc. http://www.ximian.com
10 // - implement a mechnanism for easier testing of null argument exceptions
11 // - with overloaded methods like DefineNestedType (), check the defaults
12 // on the shorter versions.
13 // - ToString on enums with the flags attribute set should print all
14 // values which match, e.g. 0 == AutoLayou,AnsiClass,NotPublic
18 using System.Threading;
19 using System.Reflection;
20 using System.Reflection.Emit;
22 using System.Security;
23 using System.Security.Permissions;
24 using System.Runtime.InteropServices;
25 using NUnit.Framework;
27 namespace MonoTests.System.Reflection.Emit
31 public class TypeBuilderTest : Assertion
33 private interface AnInterface {
45 private AssemblyBuilder assembly;
47 private ModuleBuilder module;
49 static string ASSEMBLY_NAME = "MonoTests.System.Reflection.Emit.TypeBuilderTest";
52 protected void SetUp () {
53 AssemblyName assemblyName = new AssemblyName();
54 assemblyName.Name = ASSEMBLY_NAME;
57 Thread.GetDomain().DefineDynamicAssembly(
58 assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
60 module = assembly.DefineDynamicModule("module1");
63 static int typeIndexer = 0;
65 // Return a unique type name
66 private string genTypeName () {
67 return "t" + (typeIndexer ++);
70 private string nullName () {
71 return String.Format ("{0}", (char)0);
75 public void TestAssembly () {
76 TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
77 AssertEquals ("Assembly works",
78 tb.Assembly, assembly);
82 public void TestAssemblyQualifiedName () {
83 TypeBuilder tb = module.DefineType ("A.B.C.D", TypeAttributes.Public);
85 AssertEquals ("AssemblyQualifiedName works",
86 tb.AssemblyQualifiedName, "A.B.C.D, " + assembly.GetName ().FullName);
90 public void TestAttributes () {
91 TypeAttributes attrs = TypeAttributes.Public | TypeAttributes.BeforeFieldInit;
92 TypeBuilder tb = module.DefineType (genTypeName (), attrs);
94 AssertEquals ("Attributes works",
95 tb.Attributes, attrs);
99 public void TestBaseTypeClass () {
100 TypeAttributes attrs = TypeAttributes.Public;
101 TypeBuilder tb = module.DefineType (genTypeName (), attrs);
102 AssertEquals ("BaseType defaults to Object",
103 tb.BaseType, typeof (object));
105 TypeBuilder tb2 = module.DefineType (genTypeName (), attrs, tb);
106 AssertEquals ("BaseType works",
111 public void TestBaseTypeInterface () // See bug: 71301
113 TypeBuilder tb3 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
114 AssertEquals ("Interfaces should default to no base type", null, tb3.BaseType);
118 public void TestDeclaringType () {
119 TypeAttributes attrs = 0;
120 TypeBuilder tb = module.DefineType (genTypeName (), attrs);
122 AssertEquals ("Has no declaring type",
123 null, tb.DeclaringType);
125 attrs = TypeAttributes.NestedPublic;
126 TypeBuilder tb2 = tb.DefineNestedType (genTypeName (), attrs);
127 TypeBuilder tb3 = tb2.DefineNestedType (genTypeName (), attrs);
128 AssertEquals ("DeclaringType works",
129 tb, tb3.DeclaringType.DeclaringType);
133 public void TestFullName () {
134 string name = genTypeName ();
135 TypeAttributes attrs = 0;
136 TypeBuilder tb = module.DefineType (name, attrs);
137 AssertEquals ("FullName works",
140 string name2 = genTypeName ();
141 attrs = TypeAttributes.NestedPublic;
142 TypeBuilder tb2 = tb.DefineNestedType (name2, attrs);
144 string name3 = genTypeName ();
145 attrs = TypeAttributes.NestedPublic;
146 TypeBuilder tb3 = tb2.DefineNestedType (name3, attrs);
148 AssertEquals ("FullName works on nested types",
149 name + "+" + name2 + "+" + name3, tb3.FullName);
153 [ExpectedException (typeof(NotSupportedException))]
154 public void TestGUIDIncomplete () {
155 TypeBuilder tb = module.DefineType (genTypeName ());
160 [Category("NotWorking")]
162 public void TestGUIDComplete ()
164 TypeBuilder tb = module.DefineType (genTypeName ());
166 Assert(tb.GUID != Guid.Empty);
170 [Category("NotWorking")]
171 public void TestFixedGUIDComplete ()
173 TypeBuilder tb = module.DefineType (genTypeName ());
175 Guid guid = Guid.NewGuid ();
177 ConstructorInfo guidCtor = typeof(GuidAttribute).GetConstructor(
178 new Type[] {typeof(string)});
180 CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (guidCtor,
181 new object[] { guid.ToString("D") }, new FieldInfo[0], new object[0]);
183 tb.SetCustomAttribute (caBuilder);
185 AssertEquals (guid, tb.GUID);
189 [ExpectedException (typeof(NotSupportedException))]
190 public void TestHasElementType () {
191 // According to the MSDN docs, this member works, but in reality, it
192 // returns a NotSupportedException
193 TypeBuilder tb = module.DefineType (genTypeName ());
194 bool b = tb.HasElementType;
198 public void TestIsAbstract () {
199 TypeBuilder tb = module.DefineType (genTypeName ());
201 false, tb.IsAbstract);
203 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Abstract);
205 true, tb2.IsAbstract);
209 public void TestIsAnsiClass () {
210 TypeBuilder tb = module.DefineType (genTypeName ());
212 true, tb.IsAnsiClass);
214 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.UnicodeClass);
216 false, tb2.IsAnsiClass);
220 public void TestIsArray () {
221 // How can a TypeBuilder be an array ?
222 string name = genTypeName ();
223 TypeBuilder tb = module.DefineType (name);
224 AssertEquals ("IsArray works",
229 public void TestIsAutoClass () {
230 TypeBuilder tb = module.DefineType (genTypeName ());
232 false, tb.IsAutoClass);
234 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.AutoClass);
236 true, tb2.IsAutoClass);
240 public void TestIsAutoLayout () {
241 TypeBuilder tb = module.DefineType (genTypeName ());
242 AssertEquals ("AutoLayout defaults to true",
243 true, tb.IsAutoLayout);
245 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.ExplicitLayout);
247 false, tb2.IsAutoLayout);
251 public void TestIsByRef () {
252 // How can a TypeBuilder be ByRef ?
253 TypeBuilder tb = module.DefineType (genTypeName ());
254 AssertEquals ("IsByRef works",
259 public void TestIsClass () {
260 TypeBuilder tb = module.DefineType (genTypeName ());
261 AssertEquals ("Most types are classes",
264 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
265 AssertEquals ("Interfaces are not classes",
268 TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));
269 AssertEquals ("value types are not classes",
272 TypeBuilder tb4 = module.DefineType (genTypeName (), 0, typeof (Enum));
273 AssertEquals ("enums are not classes",
278 [Category("NotWorking")]
280 public void TestIsCOMObject () {
281 TypeBuilder tb = module.DefineType (genTypeName ());
282 AssertEquals ("Probably not", false, tb.IsCOMObject);
284 tb = module.DefineType (genTypeName (), TypeAttributes.Import);
285 AssertEquals ("type with Import attribute is COM object",
286 true, tb.IsCOMObject);
290 public void TestIsContextful () {
291 TypeBuilder tb = module.DefineType (genTypeName ());
292 AssertEquals (false, tb.IsContextful);
294 TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (ContextBoundObject));
295 AssertEquals (true, tb2.IsContextful);
299 public void TestIsEnum () {
300 TypeBuilder tb = module.DefineType (genTypeName ());
301 AssertEquals (false, tb.IsEnum);
303 // This returns true under both mono and MS .NET ???
304 TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (ValueType));
305 AssertEquals ("value types are not necessary enums",
308 TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (Enum));
309 AssertEquals ("enums are enums", true, tb3.IsEnum);
313 public void TestIsExplicitLayout () {
314 TypeBuilder tb = module.DefineType (genTypeName ());
315 AssertEquals ("ExplicitLayout defaults to false",
316 false, tb.IsExplicitLayout);
318 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.ExplicitLayout);
319 AssertEquals (true, tb2.IsExplicitLayout);
323 public void TestIsImport () {
324 // How can this be true ?
325 TypeBuilder tb = module.DefineType (genTypeName ());
326 AssertEquals (false, tb.IsImport);
330 public void TestIsInterface () {
331 TypeBuilder tb = module.DefineType (genTypeName ());
332 AssertEquals ("Most types are not interfaces",
333 false, tb.IsInterface);
335 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
336 AssertEquals ("Interfaces are interfaces",
337 true, tb2.IsInterface);
339 TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));
340 AssertEquals ("value types are not interfaces",
341 false, tb3.IsInterface);
345 public void TestIsLayoutSequential () {
346 TypeBuilder tb = module.DefineType (genTypeName ());
347 AssertEquals ("SequentialLayout defaults to false",
348 false, tb.IsLayoutSequential);
350 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.SequentialLayout);
351 AssertEquals (true, tb2.IsLayoutSequential);
355 public void TestIsMarshalByRef () {
356 TypeBuilder tb = module.DefineType (genTypeName ());
357 AssertEquals (false, tb.IsMarshalByRef);
359 TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (MarshalByRefObject));
360 AssertEquals (true, tb2.IsMarshalByRef);
362 TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ContextBoundObject));
363 AssertEquals (true, tb3.IsMarshalByRef);
366 // TODO: Visibility properties
369 public void TestIsPointer () {
370 // How can this be true?
371 TypeBuilder tb = module.DefineType (genTypeName ());
372 AssertEquals (false, tb.IsPointer);
376 public void TestIsPrimitive () {
377 TypeBuilder tb = module.DefineType ("int");
378 AssertEquals (false, tb.IsPrimitive);
382 public void IsSealed () {
383 TypeBuilder tb = module.DefineType (genTypeName ());
384 AssertEquals ("Sealed defaults to false",
387 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Sealed);
388 AssertEquals ("IsSealed works", true, tb2.IsSealed);
391 static string CreateTempAssembly ()
402 path = Path.Combine (Path.GetTempPath(), "tmp" + num.ToString("x") + ".dll");
405 f = new FileStream (path, FileMode.CreateNew);
412 return "tmp" + num.ToString("x") + ".dll";
416 public void IsSerializable () {
417 TypeBuilder tb = module.DefineType (genTypeName ());
418 AssertEquals (false, tb.IsSerializable);
420 ConstructorInfo[] ctors = typeof (SerializableAttribute).GetConstructors (BindingFlags.Instance | BindingFlags.Public);
421 Assert ("SerializableAttribute should have more than 0 public instance ctors",
424 tb.SetCustomAttribute (new CustomAttributeBuilder (ctors[0], new object[0]));
425 Type createdType = tb.CreateType ();
427 string an = CreateTempAssembly ();
429 AssertEquals (true, createdType.IsSerializable);
430 File.Delete (Path.Combine (Path.GetTempPath (), an));
434 public void TestIsSpecialName () {
435 TypeBuilder tb = module.DefineType (genTypeName ());
436 AssertEquals ("SpecialName defaults to false",
437 false, tb.IsSpecialName);
439 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.SpecialName);
440 AssertEquals ("IsSpecialName works",
441 true, tb2.IsSpecialName);
445 public void TestIsUnicodeClass () {
446 TypeBuilder tb = module.DefineType (genTypeName ());
447 AssertEquals (false, tb.IsUnicodeClass);
449 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.UnicodeClass);
450 AssertEquals (true, tb2.IsUnicodeClass);
454 public void TestIsValueType () {
455 TypeBuilder tb = module.DefineType (genTypeName ());
456 AssertEquals ("Most types are not value types",
457 false, tb.IsValueType);
459 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
460 AssertEquals ("Interfaces are not value types",
461 false, tb2.IsValueType);
463 TypeBuilder tb3 = module.DefineType (genTypeName (), 0, typeof (ValueType));
464 AssertEquals ("value types are value types",
465 true, tb3.IsValueType);
467 TypeBuilder tb4 = module.DefineType (genTypeName (), 0, typeof (Enum));
468 AssertEquals ("enums are value types",
469 true, tb4.IsValueType);
473 public void TestMemberType () {
474 TypeBuilder tb = module.DefineType (genTypeName ());
475 AssertEquals ("A type is a type",
476 MemberTypes.TypeInfo, tb.MemberType);
480 public void TestModule () {
481 TypeBuilder tb = module.DefineType (genTypeName ());
482 AssertEquals ("Module works", module, tb.Module);
486 public void TestName () {
487 TypeBuilder tb = module.DefineType ("A");
488 AssertEquals ("A", tb.Name);
490 TypeBuilder tb2 = module.DefineType ("A.B.C.D.E");
491 AssertEquals ("E", tb2.Name);
493 TypeBuilder tb3 = tb2.DefineNestedType ("A");
494 AssertEquals ("A", tb3.Name);
496 /* Is .E a valid name ?
497 TypeBuilder tb4 = module.DefineType (".E");
504 public void TestNamespace () {
505 TypeBuilder tb = module.DefineType ("A");
506 AssertEquals ("", tb.Namespace);
508 TypeBuilder tb2 = module.DefineType ("A.B.C.D.E");
509 AssertEquals ("A.B.C.D", tb2.Namespace);
511 TypeBuilder tb3 = tb2.DefineNestedType ("A");
512 AssertEquals ("", tb3.Namespace);
514 /* Is .E a valid name ?
515 TypeBuilder tb4 = module.DefineType (".E");
522 public void TestPackingSize () {
523 TypeBuilder tb = module.DefineType (genTypeName ());
524 AssertEquals (PackingSize.Unspecified, tb.PackingSize);
526 TypeBuilder tb2 = module.DefineType (genTypeName (), 0, typeof (object),
527 PackingSize.Size16, 16);
528 AssertEquals (PackingSize.Size16, tb2.PackingSize);
532 public void TestReflectedType () {
533 // It is the same as DeclaringType, but why?
534 TypeBuilder tb = module.DefineType (genTypeName ());
535 AssertEquals (null, tb.ReflectedType);
537 TypeBuilder tb2 = tb.DefineNestedType (genTypeName ());
538 AssertEquals (tb, tb2.ReflectedType);
542 [ExpectedException (typeof(ArgumentNullException))]
543 public void TestSetParentNull ()
545 TypeBuilder tb = module.DefineType (genTypeName ());
550 public void TestSetParentIncomplete ()
552 TypeBuilder tb = module.DefineType (genTypeName ());
553 tb.SetParent (typeof(Attribute));
554 AssertEquals (typeof(Attribute), tb.BaseType);
558 [ExpectedException (typeof(InvalidOperationException))]
559 public void TestSetParentComplete ()
561 TypeBuilder tb = module.DefineType (genTypeName ());
563 tb.SetParent (typeof(Attribute));
567 public void TestSize () {
569 TypeBuilder tb = module.DefineType (genTypeName ());
570 AssertEquals (0, tb.Size);
572 AssertEquals (0, tb.Size);
576 TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (object),
577 PackingSize.Size16, 32);
578 AssertEquals (32, tb.Size);
583 [ExpectedException (typeof(NotSupportedException))]
584 public void TestTypeHandle () {
585 TypeBuilder tb = module.DefineType (genTypeName ());
586 RuntimeTypeHandle handle = tb.TypeHandle;
590 [ExpectedException (typeof(NotSupportedException))]
591 public void TestTypeInitializerIncomplete ()
593 TypeBuilder tb = module.DefineType (genTypeName ());
594 ConstructorInfo cb = tb.TypeInitializer;
598 public void TestTypeInitializerComplete ()
600 TypeBuilder tb = module.DefineType (genTypeName ());
602 ConstructorInfo cb = tb.TypeInitializer;
606 public void TestTypeToken () {
607 TypeBuilder tb = module.DefineType (genTypeName ());
608 TypeToken token = tb.TypeToken;
612 [Category("NotWorking")]
613 public void TestUnderlyingSystemType () {
615 TypeBuilder tb = module.DefineType (genTypeName ());
616 AssertEquals ("For non-enums this equals itself",
617 tb, tb.UnderlyingSystemType);
620 TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
621 AssertEquals (tb, tb.UnderlyingSystemType);
624 TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (ValueType));
625 AssertEquals (tb, tb.UnderlyingSystemType);
629 TypeBuilder tb = module.DefineType (genTypeName (), 0, typeof (Enum));
631 Type t = tb.UnderlyingSystemType;
634 catch (InvalidOperationException) {
637 tb.DefineField ("val", typeof (int), 0);
638 AssertEquals (typeof (int), tb.UnderlyingSystemType);
643 public void TestAddInterfaceImplementation () {
644 TypeBuilder tb = module.DefineType (genTypeName ());
646 tb.AddInterfaceImplementation (null);
649 catch (ArgumentNullException) {
652 tb.AddInterfaceImplementation (typeof (AnInterface));
653 tb.AddInterfaceImplementation (typeof (AnInterface));
655 Type t = tb.CreateType ();
656 AssertEquals ("Should merge identical interfaces",
657 tb.GetInterfaces ().Length, 1);
659 // Can not be called on a created type
661 tb.AddInterfaceImplementation (typeof (AnInterface));
664 catch (InvalidOperationException) {
669 [Category("NotWorking")]
670 public void TestCreateType () {
671 // TODO: LOTS OF TEST SHOULD GO THERE
672 TypeBuilder tb = module.DefineType (genTypeName ());
675 // Can not be called on a created type
680 catch (InvalidOperationException) {
685 public void TestDefineConstructor () {
686 TypeBuilder tb = module.DefineType (genTypeName ());
688 ConstructorBuilder cb = tb.DefineConstructor (0, 0, null);
689 cb.GetILGenerator ().Emit (OpCodes.Ret);
692 // Can not be called on a created type
694 tb.DefineConstructor (0, 0, null);
697 catch (InvalidOperationException) {
702 public void TestDefineDefaultConstructor () {
703 TypeBuilder tb = module.DefineType (genTypeName ());
704 tb.DefineDefaultConstructor (0);
707 // Can not be called on a created type, altough the MSDN docs does not mention this
709 tb.DefineDefaultConstructor (0);
712 catch (InvalidOperationException) {
717 [ExpectedException (typeof(InvalidOperationException))]
718 public void TestDefineDefaultConstructorParent () {
719 TypeBuilder tb = module.DefineType (genTypeName ());
720 tb.DefineConstructor (MethodAttributes.Public,
721 CallingConventions.Standard,
722 new Type[] { typeof(string) });
723 Type type = tb.CreateType ();
725 // create TypeBuilder for type that derived from the
726 // previously created type (which has no default ctor)
727 tb = module.DefineType (genTypeName (), TypeAttributes.Class
728 | TypeAttributes.Public, type);
730 // you cannot create a type with a default ctor that
731 // derives from a type without a default ctor
736 public void TestDefineEvent () {
737 TypeBuilder tb = module.DefineType (genTypeName ());
739 // Test invalid arguments
741 tb.DefineEvent (null, 0, typeof (int));
744 catch (ArgumentNullException) {
748 tb.DefineEvent ("FOO", 0, null);
751 catch (ArgumentNullException) {
755 tb.DefineEvent ("", 0, typeof (int));
758 catch (ArgumentException) {
762 // Can not be called on a created type
764 tb.DefineEvent ("BAR", 0, typeof (int));
767 catch (InvalidOperationException) {
772 public void TestDefineField () {
773 TypeBuilder tb = module.DefineType (genTypeName ());
775 // Check invalid arguments
777 tb.DefineField (null, typeof (int), 0);
780 catch (ArgumentNullException) {
784 tb.DefineField ("", typeof (int), 0);
787 catch (ArgumentException) {
791 // Strangely, 'A<NULL>' is accepted...
792 string name = String.Format ("{0}", (char)0);
793 tb.DefineField (name, typeof (int), 0);
794 Fail ("Names with embedded nulls should be rejected");
796 catch (ArgumentException) {
800 tb.DefineField ("A", typeof (void), 0);
803 catch (ArgumentException) {
807 // Can not be called on a created type
809 tb.DefineField ("B", typeof (int), 0);
812 catch (InvalidOperationException) {
817 public void TestDefineInitializedData () {
818 TypeBuilder tb = module.DefineType (genTypeName ());
820 // Check invalid arguments
822 tb.DefineInitializedData (null, new byte[1], 0);
825 catch (ArgumentNullException) {
829 tb.DefineInitializedData ("FOO", null, 0);
832 catch (ArgumentNullException) {
836 tb.DefineInitializedData ("", new byte[1], 0);
839 catch (ArgumentException) {
842 // The size of the data is less than or equal to zero ???
844 tb.DefineInitializedData ("BAR", new byte[0], 0);
847 catch (ArgumentException) {
851 string name = String.Format ("{0}", (char)0);
852 tb.DefineInitializedData (name, new byte[1], 0);
853 Fail ("Names with embedded nulls should be rejected");
855 catch (ArgumentException) {
860 // Can not be called on a created type, altough the MSDN docs does not mention this
862 tb.DefineInitializedData ("BAR2", new byte[1], 0);
865 catch (InvalidOperationException) {
870 public void DefineUninitializedDataInvalidArgs () {
871 TypeBuilder tb = module.DefineType (genTypeName ());
874 tb.DefineUninitializedData (null, 1, 0);
877 catch (ArgumentNullException) {
881 tb.DefineUninitializedData ("", 1, 0);
884 catch (ArgumentException) {
887 // The size of the data is less than or equal to zero ???
889 tb.DefineUninitializedData ("BAR", 0, 0);
892 catch (ArgumentException) {
896 string name = String.Format ("{0}", (char)0);
897 tb.DefineUninitializedData (name, 1, 0);
898 Fail ("Names with embedded nulls should be rejected");
900 catch (ArgumentException) {
905 [ExpectedException (typeof (InvalidOperationException))]
906 public void DefineUninitializedDataAlreadyCreated () {
907 TypeBuilder tb = module.DefineType (genTypeName ());
910 tb.DefineUninitializedData ("BAR2", 1, 0);
914 public void DefineUninitializedData () {
915 TypeBuilder tb = module.DefineType (genTypeName ());
917 tb.DefineUninitializedData ("foo", 4, FieldAttributes.Public);
919 Type t = tb.CreateType ();
921 object o = Activator.CreateInstance (t);
923 FieldInfo fi = t.GetField ("foo");
925 object fieldVal = fi.GetValue (o);
927 IntPtr ptr = Marshal.AllocHGlobal (4);
928 Marshal.StructureToPtr (fieldVal, ptr, true);
929 Marshal.FreeHGlobal (ptr);
933 public void TestDefineMethod () {
934 TypeBuilder tb = module.DefineType (genTypeName ());
936 // Check invalid arguments
938 tb.DefineMethod (null, 0, null, null);
941 catch (ArgumentNullException) {
945 tb.DefineMethod ("", 0, null, null);
948 catch (ArgumentException) {
951 // Check non-virtual methods on an interface
952 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
954 tb2.DefineMethod ("FOO", MethodAttributes.Abstract, null, null);
957 catch (ArgumentException) {
960 // Check static methods on an interface
961 tb2.DefineMethod ("BAR", MethodAttributes.Public | MethodAttributes.Static,
966 // Can not be called on a created type
968 tb.DefineMethod ("bar", 0, null, null);
971 catch (InvalidOperationException) {
975 // TODO: DefineMethodOverride
978 public void TestDefineNestedType () {
979 TypeBuilder tb = module.DefineType (genTypeName ());
981 // Check invalid arguments
983 tb.DefineNestedType (null);
984 Fail ("Should reject null name");
986 catch (ArgumentNullException) {
990 tb.DefineNestedType ("");
991 Fail ("Should reject empty name");
993 catch (ArgumentException) {
997 tb.DefineNestedType (nullName ());
998 Fail ("Should reject name with embedded 0s");
1000 catch (ArgumentException) {
1003 // If I fix the code so this works then mcs breaks -> how can mcs
1004 // works under MS .NET in the first place ???
1007 tb.DefineNestedType ("AA", TypeAttributes.Public, null, null);
1008 Fail ("Nested visibility must be specified.");
1010 catch (ArgumentException) {
1015 tb.DefineNestedType ("BB", TypeAttributes.NestedPublic, null,
1017 Fail ("Should reject empty interface");
1019 catch (ArgumentException) {
1022 // I think this should reject non-interfaces, but it does not
1023 tb.DefineNestedType ("BB", TypeAttributes.NestedPublic, null,
1024 new Type[1] { typeof (object) });
1026 // Normal invocation
1027 tb.DefineNestedType ("Nest");
1031 // According to the MSDN docs, this cannnot be called after the type
1032 // is created, but it works.
1033 tb.DefineNestedType ("Nest2");
1035 // According to the MSDN docs, a Sealed class can't contain nested
1036 // types, but this is not true
1037 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Sealed);
1038 tb2.DefineNestedType ("AA");
1040 // According to the MSDN docs, interfaces can only contain interfaces,
1041 // but this is not true
1042 TypeBuilder tb3 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
1044 tb3.DefineNestedType ("AA");
1046 // Check shorter versions
1048 TypeBuilder nested = tb.DefineNestedType ("N1");
1050 AssertEquals (nested.Name, "N1");
1051 AssertEquals (nested.BaseType, typeof (object));
1052 AssertEquals (nested.Attributes, TypeAttributes.NestedPrivate);
1053 AssertEquals (nested.GetInterfaces ().Length, 0);
1060 public void TestDefinePInvokeMethod () {
1061 TypeBuilder tb = module.DefineType (genTypeName ());
1063 tb.DefinePInvokeMethod ("A", "B", "C", 0, 0, null, null, 0, 0);
1065 // Try invalid parameters
1067 tb.DefinePInvokeMethod (null, "B", "C", 0, 0, null, null, 0, 0);
1070 catch (ArgumentNullException) {
1074 // Try invalid attributes
1076 tb.DefinePInvokeMethod ("A2", "B", "C", MethodAttributes.Abstract, 0, null, null, 0, 0);
1078 catch (ArgumentException) {
1081 // Try an interface parent
1082 TypeBuilder tb2 = module.DefineType (genTypeName (), TypeAttributes.Interface | TypeAttributes.Abstract);
1085 tb2.DefinePInvokeMethod ("A", "B", "C", 0, 0, null, null, 0, 0);
1087 catch (ArgumentException) {
1092 public void TestDefineProperty () {
1093 TypeBuilder tb = module.DefineType (genTypeName ());
1095 // Check null parameter types
1097 tb.DefineProperty ("A", 0, null, new Type[1]);
1099 catch (ArgumentNullException) {
1104 [ExpectedException (typeof(NotSupportedException))]
1105 [Category("NotWorking")]
1106 public void TestIsDefinedIncomplete () {
1107 TypeBuilder tb = module.DefineType (genTypeName ());
1108 tb.IsDefined (typeof (int), true);
1112 public void TestIsDefinedComplete () {
1113 TypeBuilder tb = module.DefineType (genTypeName ());
1115 ConstructorInfo obsoleteCtor = typeof(ObsoleteAttribute).GetConstructor(
1116 new Type[] {typeof(string)});
1118 CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (obsoleteCtor,
1119 new object[] { "obsolete message" }, new FieldInfo[0], new object[0]);
1121 tb.SetCustomAttribute (caBuilder);
1123 AssertEquals (true, tb.IsDefined (typeof(ObsoleteAttribute), false));
1127 [ExpectedException (typeof(NotSupportedException))]
1128 public void TestGetCustomAttributesIncomplete ()
1130 TypeBuilder tb = module.DefineType (genTypeName ());
1131 tb.GetCustomAttributes (false);
1135 public void TestGetCustomAttributesComplete ()
1137 TypeBuilder tb = module.DefineType (genTypeName ());
1139 ConstructorInfo guidCtor = typeof(GuidAttribute).GetConstructor (
1140 new Type[] { typeof(string) });
1142 CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (guidCtor,
1143 new object[] { Guid.NewGuid ().ToString ("D") }, new FieldInfo[0], new object[0]);
1145 tb.SetCustomAttribute (caBuilder);
1148 AssertEquals (1, tb.GetCustomAttributes (false).Length);
1152 [ExpectedException (typeof(NotSupportedException))]
1153 public void TestGetCustomAttributesOfTypeIncomplete ()
1155 TypeBuilder tb = module.DefineType (genTypeName ());
1156 tb.GetCustomAttributes (typeof(ObsoleteAttribute), false);
1160 public void TestGetCustomAttributesOfTypeComplete ()
1162 TypeBuilder tb = module.DefineType (genTypeName ());
1164 ConstructorInfo guidCtor = typeof(GuidAttribute).GetConstructor (
1165 new Type[] { typeof(string) });
1167 CustomAttributeBuilder caBuilder = new CustomAttributeBuilder (guidCtor,
1168 new object[] { Guid.NewGuid ().ToString ("D") }, new FieldInfo[0], new object[0]);
1170 tb.SetCustomAttribute (caBuilder);
1173 AssertEquals (1, tb.GetCustomAttributes (typeof(GuidAttribute), false).Length);
1174 AssertEquals (0, tb.GetCustomAttributes (typeof(ObsoleteAttribute), false).Length);
1178 [ExpectedException (typeof(ArgumentNullException))]
1179 public void TestGetCustomAttributesOfNullTypeComplete ()
1181 TypeBuilder tb = module.DefineType (genTypeName ());
1183 tb.GetCustomAttributes (null, false);
1187 [ExpectedException (typeof(NotSupportedException))]
1188 [Ignore("mcs depends on this")]
1189 public void TestGetEventsIncomplete () {
1190 TypeBuilder tb = module.DefineType (genTypeName ());
1195 public void TestGetEventsComplete () {
1196 TypeBuilder tb = module.DefineType (genTypeName ());
1198 MethodBuilder onclickMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
1199 typeof(void), new Type[] { typeof(Object) });
1200 onclickMethod.GetILGenerator ().Emit (OpCodes.Ret);
1202 // create public event
1203 EventBuilder eventbuilder = tb.DefineEvent ("Change", EventAttributes.None,
1204 typeof(ResolveEventHandler));
1205 eventbuilder.SetRaiseMethod (onclickMethod);
1207 Type emittedType = tb.CreateType ();
1209 AssertEquals (1, tb.GetEvents ().Length);
1210 AssertEquals (tb.GetEvents ().Length, emittedType.GetEvents ().Length);
1215 [ExpectedException (typeof(NotSupportedException))]
1216 [Ignore("mcs depends on this")]
1217 public void TestGetEventsFlagsIncomplete () {
1218 TypeBuilder tb = module.DefineType (genTypeName ());
1219 tb.GetEvents (BindingFlags.Public);
1223 public void TestGetEventsFlagsComplete () {
1224 TypeBuilder tb = module.DefineType (genTypeName ());
1226 MethodBuilder onchangeMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
1227 typeof(void), new Type[] { typeof(Object) });
1228 onchangeMethod.GetILGenerator ().Emit (OpCodes.Ret);
1230 // create public event
1231 EventBuilder changeEvent = tb.DefineEvent ("Change", EventAttributes.None,
1232 typeof(ResolveEventHandler));
1233 changeEvent.SetRaiseMethod (onchangeMethod);
1235 // create non-public event
1236 EventBuilder redoChangeEvent = tb.DefineEvent ("RedoChange", EventAttributes.None,
1237 typeof(ResolveEventHandler));
1239 Type emittedType = tb.CreateType ();
1241 AssertEquals (1, tb.GetEvents (BindingFlags.Instance | BindingFlags.Public).Length);
1242 AssertEquals (1, tb.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1243 AssertEquals (2, tb.GetEvents (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Length);
1244 AssertEquals (tb.GetEvents (BindingFlags.Instance | BindingFlags.Public).Length,
1245 emittedType.GetEvents (BindingFlags.Instance | BindingFlags.Public).Length);
1246 AssertEquals (tb.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic).Length,
1247 emittedType.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1248 AssertEquals (tb.GetEvents (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Length,
1249 emittedType.GetEvents (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Length);
1253 [ExpectedException (typeof(NotSupportedException))]
1254 [Ignore("mcs depends on this")]
1255 public void TestGetEventIncomplete () {
1256 TypeBuilder tb = module.DefineType (genTypeName ());
1257 tb.GetEvent ("FOO");
1261 public void TestGetEventComplete () {
1262 TypeBuilder tb = module.DefineType (genTypeName ());
1264 MethodBuilder onclickMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
1265 typeof(void), new Type[] { typeof(Object) });
1266 onclickMethod.GetILGenerator ().Emit (OpCodes.Ret);
1268 EventBuilder eventbuilder = tb.DefineEvent ("Change", EventAttributes.None,
1269 typeof(ResolveEventHandler));
1270 eventbuilder.SetRaiseMethod (onclickMethod);
1272 Type emittedType = tb.CreateType ();
1274 AssertNotNull (tb.GetEvent ("Change"));
1275 AssertEquals (tb.GetEvent ("Change"), emittedType.GetEvent ("Change"));
1276 AssertNull (tb.GetEvent ("NotChange"));
1277 AssertEquals (tb.GetEvent ("NotChange"), emittedType.GetEvent ("NotChange"));
1281 [ExpectedException (typeof(NotSupportedException))]
1282 [Ignore("mcs depends on this")]
1283 public void TestGetEventFlagsIncomplete () {
1284 TypeBuilder tb = module.DefineType (genTypeName ());
1285 tb.GetEvent ("FOO", BindingFlags.Public);
1289 public void TestGetEventFlagsComplete () {
1290 TypeBuilder tb = module.DefineType (genTypeName ());
1292 MethodBuilder onclickMethod = tb.DefineMethod ("OnChange", MethodAttributes.Public,
1293 typeof(void), new Type[] { typeof(Object) });
1294 onclickMethod.GetILGenerator ().Emit (OpCodes.Ret);
1296 EventBuilder eventbuilder = tb.DefineEvent ("Change", EventAttributes.None,
1297 typeof(ResolveEventHandler));
1298 eventbuilder.SetRaiseMethod (onclickMethod);
1300 Type emittedType = tb.CreateType ();
1302 AssertNotNull (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.Public));
1303 AssertEquals (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.Public),
1304 emittedType.GetEvent ("Change", BindingFlags.Instance | BindingFlags.Public));
1305 AssertNull (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.NonPublic));
1306 AssertEquals (tb.GetEvent ("Change", BindingFlags.Instance | BindingFlags.NonPublic),
1307 emittedType.GetEvent ("Change", BindingFlags.Instance | BindingFlags.NonPublic));
1311 [ExpectedException (typeof(NotSupportedException))]
1312 [Ignore("mcs depends on this")]
1313 public void TestGetFieldsIncomplete () {
1314 TypeBuilder tb = module.DefineType (genTypeName ());
1319 public void TestGetFieldsComplete () {
1320 TypeBuilder tb = module.DefineType (genTypeName ());
1321 tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
1323 Type emittedType = tb.CreateType ();
1325 AssertEquals (1, tb.GetFields ().Length);
1326 AssertEquals (tb.GetFields ().Length, emittedType.GetFields().Length);
1330 [ExpectedException (typeof(NotSupportedException))]
1331 [Ignore("mcs depends on this")]
1332 public void TestGetFieldsFlagsIncomplete () {
1333 TypeBuilder tb = module.DefineType (genTypeName ());
1334 tb.GetFields (BindingFlags.Instance | BindingFlags.Public);
1338 public void TestGetFieldsFlagsComplete () {
1339 TypeBuilder tb = module.DefineType (genTypeName ());
1340 tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
1342 Type emittedType = tb.CreateType ();
1344 AssertEquals (1, tb.GetFields (BindingFlags.Instance | BindingFlags.Public).Length);
1345 AssertEquals (tb.GetFields (BindingFlags.Instance | BindingFlags.Public).Length,
1346 emittedType.GetFields (BindingFlags.Instance | BindingFlags.Public).Length);
1347 AssertEquals (0, tb.GetFields (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1348 AssertEquals (tb.GetFields (BindingFlags.Instance | BindingFlags.NonPublic).Length,
1349 emittedType.GetFields (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1353 [ExpectedException (typeof(NotSupportedException))]
1354 [Ignore("mcs depends on this")]
1355 public void TestGetFieldIncomplete () {
1356 TypeBuilder tb = module.DefineType (genTypeName ());
1357 tb.GetField ("test");
1361 public void TestGetFieldComplete () {
1362 TypeBuilder tb = module.DefineType (genTypeName ());
1363 tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
1365 Type emittedType = tb.CreateType ();
1367 AssertNotNull (tb.GetField ("TestField"));
1368 AssertEquals (tb.GetField ("TestField").Name, emittedType.GetField ("TestField").Name);
1369 //AssertNull (tb.GetField ("TestOtherField"));
1370 //AssertEquals (tb.GetField ("TestOtherField").Name,
1371 // emittedType.GetField ("TestOtherField").Name);
1375 [ExpectedException (typeof(NotSupportedException))]
1376 [Ignore("mcs depends on this")]
1377 public void TestGetFieldFlagsIncomplete () {
1378 TypeBuilder tb = module.DefineType (genTypeName ());
1379 tb.GetField ("test", BindingFlags.Public);
1383 public void TestGetFieldFlagsComplete () {
1384 TypeBuilder tb = module.DefineType (genTypeName ());
1385 tb.DefineField ("TestField", typeof(int), FieldAttributes.Public);
1387 Type emittedType = tb.CreateType ();
1389 AssertNotNull (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.Public));
1390 AssertEquals (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.Public).Name,
1391 emittedType.GetField ("TestField", BindingFlags.Instance | BindingFlags.Public).Name);
1392 AssertNull (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.NonPublic));
1393 AssertEquals (tb.GetField ("TestField", BindingFlags.Instance | BindingFlags.NonPublic),
1394 emittedType.GetField ("TestField", BindingFlags.Instance | BindingFlags.NonPublic));
1398 [ExpectedException (typeof(NotSupportedException))]
1399 [Ignore("mcs depends on this")]
1400 public void TestGetPropertiesIncomplete () {
1401 TypeBuilder tb = module.DefineType (genTypeName ());
1402 tb.GetProperties ();
1406 public void TestGetPropertiesComplete () {
1407 TypeBuilder tb = module.DefineType (genTypeName ());
1408 DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
1410 Type emittedType = tb.CreateType ();
1412 AssertEquals (1, tb.GetProperties ().Length);
1413 AssertEquals (tb.GetProperties ().Length, emittedType.GetProperties ().Length);
1417 [ExpectedException (typeof(NotSupportedException))]
1418 [Ignore("mcs depends on this")]
1419 public void TestGetPropertiesFlagsIncomplete () {
1420 TypeBuilder tb = module.DefineType (genTypeName ());
1421 tb.GetProperties (BindingFlags.Public);
1425 public void TestGetPropertiesFlagsComplete () {
1426 TypeBuilder tb = module.DefineType (genTypeName ());
1427 DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
1429 Type emittedType = tb.CreateType ();
1431 AssertEquals (1, tb.GetProperties (BindingFlags.Instance | BindingFlags.Public).Length);
1432 AssertEquals (tb.GetProperties (BindingFlags.Instance | BindingFlags.Public).Length,
1433 emittedType.GetProperties (BindingFlags.Instance | BindingFlags.Public).Length);
1434 AssertEquals (0, tb.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1435 AssertEquals (tb.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic).Length,
1436 emittedType.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1440 [ExpectedException (typeof(NotSupportedException))]
1441 public void TestGetPropertyIncomplete () {
1442 TypeBuilder tb = module.DefineType (genTypeName ());
1443 tb.GetProperty ("test");
1447 public void TestGetPropertyComplete () {
1448 TypeBuilder tb = module.DefineType (genTypeName ());
1449 DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
1451 Type emittedType = tb.CreateType ();
1453 AssertNotNull (emittedType.GetProperty ("CustomerName"));
1454 AssertNull (emittedType.GetProperty ("OtherCustomerName"));
1457 tb.GetProperty ("CustomerName");
1459 } catch (NotSupportedException) {}
1463 [ExpectedException (typeof(NotSupportedException))]
1464 public void TestGetPropertyFlagsIncomplete () {
1465 TypeBuilder tb = module.DefineType (genTypeName ());
1466 tb.GetProperty ("test", BindingFlags.Public);
1470 public void TestGetPropertyFlagsComplete () {
1471 TypeBuilder tb = module.DefineType (genTypeName ());
1472 DefineStringProperty (tb, "CustomerName", "customerName", MethodAttributes.Public);
1474 Type emittedType = tb.CreateType ();
1476 AssertNotNull (emittedType.GetProperty ("CustomerName", BindingFlags.Instance |
1477 BindingFlags.Public));
1478 AssertNull (emittedType.GetProperty ("CustomerName", BindingFlags.Instance |
1479 BindingFlags.NonPublic));
1482 tb.GetProperty ("CustomerName", BindingFlags.Instance | BindingFlags.Public);
1485 catch (NotSupportedException) { }
1489 [ExpectedException (typeof(NotSupportedException))]
1490 [Ignore("mcs depends on this")]
1491 public void TestGetMethodsIncomplete () {
1492 TypeBuilder tb = module.DefineType (genTypeName ());
1497 [Category("NotWorking")]
1498 public void TestGetMethodsComplete () {
1499 TypeBuilder tb = module.DefineType (genTypeName ());
1500 MethodBuilder helloMethod = tb.DefineMethod ("HelloMethod",
1501 MethodAttributes.Public, typeof(string), new Type[0]);
1502 ILGenerator helloMethodIL = helloMethod.GetILGenerator ();
1503 helloMethodIL.Emit (OpCodes.Ldstr, "Hi! ");
1504 helloMethodIL.Emit (OpCodes.Ldarg_1);
1505 MethodInfo infoMethod = typeof(string).GetMethod ("Concat",
1506 new Type[] { typeof(string), typeof(string) });
1507 helloMethodIL.Emit (OpCodes.Call, infoMethod);
1508 helloMethodIL.Emit (OpCodes.Ret);
1510 Type emittedType = tb.CreateType ();
1512 AssertEquals (typeof(object).GetMethods (BindingFlags.Public | BindingFlags.Instance).Length + 1,
1513 tb.GetMethods ().Length);
1514 AssertEquals (tb.GetMethods ().Length, emittedType.GetMethods ().Length);
1518 [ExpectedException (typeof(NotSupportedException))]
1519 [Ignore("mcs depends on this")]
1520 public void TestGetMethodsFlagsIncomplete () {
1521 TypeBuilder tb = module.DefineType (genTypeName ());
1522 tb.GetMethods (BindingFlags.Public);
1526 public void TestGetMethodsFlagsComplete () {
1527 TypeBuilder tb = module.DefineType (genTypeName ());
1528 MethodBuilder helloMethod = tb.DefineMethod ("HelloMethod",
1529 MethodAttributes.Public, typeof(string), new Type[0]);
1530 ILGenerator helloMethodIL = helloMethod.GetILGenerator ();
1531 helloMethodIL.Emit (OpCodes.Ldstr, "Hi! ");
1532 helloMethodIL.Emit (OpCodes.Ldarg_1);
1533 MethodInfo infoMethod = typeof(string).GetMethod ("Concat",
1534 new Type[] { typeof(string), typeof(string) });
1535 helloMethodIL.Emit (OpCodes.Call, infoMethod);
1536 helloMethodIL.Emit (OpCodes.Ret);
1538 Type emittedType = tb.CreateType ();
1540 AssertEquals (1, tb.GetMethods (BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).Length);
1541 AssertEquals (tb.GetMethods (BindingFlags.Instance | BindingFlags.Public).Length,
1542 emittedType.GetMethods (BindingFlags.Instance | BindingFlags.Public).Length);
1543 AssertEquals (0, tb.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).Length);
1544 AssertEquals (tb.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic).Length,
1545 emittedType.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1549 [ExpectedException (typeof(NotSupportedException))]
1550 public void TestGetMemberIncomplete () {
1551 TypeBuilder tb = module.DefineType (genTypeName ());
1552 tb.GetMember ("FOO", MemberTypes.All, BindingFlags.Public);
1556 public void TestGetMemberComplete () {
1557 TypeBuilder tb = module.DefineType (genTypeName ());
1558 tb.DefineField ("FOO", typeof(int), FieldAttributes.Private);
1560 Type emittedType = tb.CreateType ();
1562 AssertEquals (1, tb.GetMember ("FOO", MemberTypes.Field, BindingFlags.Instance | BindingFlags.NonPublic).Length);
1563 AssertEquals (0, tb.GetMember ("FOO", MemberTypes.Field, BindingFlags.Instance | BindingFlags.Public).Length);
1567 [ExpectedException (typeof(NotSupportedException))]
1568 public void TestGetMembersIncomplete () {
1569 TypeBuilder tb = module.DefineType (genTypeName ());
1574 public void TestGetMembersComplete () {
1575 TypeBuilder tb = module.DefineType (genTypeName ());
1576 Type emittedType = tb.CreateType ();
1578 AssertEquals (tb.GetMembers ().Length, emittedType.GetMembers ().Length);
1582 [ExpectedException (typeof(NotSupportedException))]
1583 public void TestGetMembersFlagsIncomplete () {
1584 TypeBuilder tb = module.DefineType (genTypeName ());
1585 tb.GetMembers (BindingFlags.Public);
1589 public void TestGetMembersFlagsComplete () {
1590 TypeBuilder tb = module.DefineType (genTypeName ());
1591 tb.DefineField ("FOO", typeof(int), FieldAttributes.Public);
1593 Type emittedType = tb.CreateType ();
1595 Assert (tb.GetMembers (BindingFlags.Instance | BindingFlags.Public).Length != 0);
1596 AssertEquals (tb.GetMembers (BindingFlags.Instance | BindingFlags.Public).Length,
1597 emittedType.GetMembers (BindingFlags.Instance | BindingFlags.Public).Length);
1598 AssertEquals (tb.GetMembers (BindingFlags.Instance | BindingFlags.NonPublic).Length,
1599 emittedType.GetMembers (BindingFlags.Instance | BindingFlags.NonPublic).Length);
1603 [ExpectedException (typeof(NotSupportedException))]
1604 public void TestGetInterfaceIncomplete () {
1605 TypeBuilder tb = module.DefineType (genTypeName ());
1606 tb.GetInterface ("FOO", true);
1610 public void TestGetInterfaces () {
1611 TypeBuilder tb = module.DefineType (genTypeName ());
1612 Type[] interfaces = tb.GetInterfaces ();
1613 AssertEquals (0, interfaces.Length);
1615 TypeBuilder tbInterface = module.DefineType (genTypeName (), TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract);
1616 Type emittedInterface = tbInterface.CreateType ();
1618 tb = module.DefineType (genTypeName (), TypeAttributes.Public, typeof(object), new Type[] { emittedInterface });
1619 interfaces = tb.GetInterfaces ();
1620 AssertEquals (1, interfaces.Length);
1624 [ExpectedException (typeof (InvalidOperationException))]
1625 public void TestAddDeclarativeSecurityAlreadyCreated () {
1626 TypeBuilder tb = module.DefineType (genTypeName ());
1629 PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
1630 tb.AddDeclarativeSecurity (SecurityAction.Demand, set);
1634 [ExpectedException (typeof (ArgumentNullException))]
1635 public void TestAddDeclarativeSecurityNullPermissionSet () {
1636 TypeBuilder tb = module.DefineType (genTypeName ());
1638 tb.AddDeclarativeSecurity (SecurityAction.Demand, null);
1642 public void TestAddDeclarativeSecurityInvalidAction () {
1643 TypeBuilder tb = module.DefineType (genTypeName ());
1645 SecurityAction[] actions = new SecurityAction [] {
1646 SecurityAction.RequestMinimum,
1647 SecurityAction.RequestOptional,
1648 SecurityAction.RequestRefuse };
1649 PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
1651 foreach (SecurityAction action in actions) {
1653 tb.AddDeclarativeSecurity (action, set);
1655 } catch (ArgumentOutOfRangeException) {
1661 [ExpectedException (typeof (InvalidOperationException))]
1662 public void TestAddDeclarativeSecurityDuplicateAction () {
1663 TypeBuilder tb = module.DefineType (genTypeName ());
1665 PermissionSet set = new PermissionSet (PermissionState.Unrestricted);
1666 tb.AddDeclarativeSecurity (SecurityAction.Demand, set);
1667 tb.AddDeclarativeSecurity (SecurityAction.Demand, set);
1671 public void TestEnums () {
1672 TypeAttributes typeAttrs = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;
1673 TypeBuilder enumToCreate = module.DefineType(genTypeName (), typeAttrs,
1675 enumToCreate.SetCustomAttribute (new CustomAttributeBuilder (typeof (FlagsAttribute).GetConstructors ()[0], new Type [0]));
1676 // add value__ field, see DefineEnum method of ModuleBuilder
1677 enumToCreate.DefineField("value__", typeof(Int32),
1678 FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
1681 FieldBuilder fb = enumToCreate.DefineField("A", enumToCreate,
1682 FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
1683 fb.SetConstant((Int32) 0);
1685 fb = enumToCreate.DefineField("B", enumToCreate,
1686 FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
1687 fb.SetConstant((Int32) 1);
1689 fb = enumToCreate.DefineField("C", enumToCreate,
1690 FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
1691 fb.SetConstant((Int32) 2);
1693 Type enumType = enumToCreate.CreateType();
1695 object enumVal = Enum.ToObject(enumType, (Int32) 3);
1697 AssertEquals ("B, C", enumVal.ToString ());
1698 AssertEquals (3, (Int32)enumVal);
1702 public void DefineEnum () {
1703 TypeBuilder typeBuilder = module.DefineType (genTypeName (),
1704 TypeAttributes.Public);
1705 EnumBuilder enumBuilder = module.DefineEnum (genTypeName (),
1706 TypeAttributes.Public, typeof(int));
1707 typeBuilder.DefineField ("myField", enumBuilder, FieldAttributes.Private);
1708 enumBuilder.CreateType();
1709 typeBuilder.CreateType();
1713 [ExpectedException(typeof(TypeLoadException))]
1714 [Category("NotWorking")]
1715 public void DefineEnumThrowIfTypeBuilderCalledBeforeEnumBuilder () {
1716 TypeBuilder typeBuilder = module.DefineType (genTypeName (),
1717 TypeAttributes.Public);
1718 EnumBuilder enumBuilder = module.DefineEnum (genTypeName (),
1719 TypeAttributes.Public, typeof(int));
1720 typeBuilder.DefineField ("myField", enumBuilder, FieldAttributes.Private);
1721 typeBuilder.CreateType();
1722 enumBuilder.CreateType();
1725 private void DefineStringProperty (TypeBuilder tb, string propertyName, string fieldName, MethodAttributes methodAttribs) {
1726 // define the field holding the property value
1727 FieldBuilder fieldBuilder = tb.DefineField (fieldName,
1728 typeof(string), FieldAttributes.Private);
1730 PropertyBuilder propertyBuilder = tb.DefineProperty (
1731 propertyName, PropertyAttributes.HasDefault, typeof(string),
1732 new Type[] { typeof(string) });
1734 // First, we'll define the behavior of the "get" property for CustomerName as a method.
1735 MethodBuilder getMethodBuilder = tb.DefineMethod ("Get" + propertyName,
1740 ILGenerator getIL = getMethodBuilder.GetILGenerator ();
1742 getIL.Emit (OpCodes.Ldarg_0);
1743 getIL.Emit (OpCodes.Ldfld, fieldBuilder);
1744 getIL.Emit (OpCodes.Ret);
1746 // Now, we'll define the behavior of the "set" property for CustomerName.
1747 MethodBuilder setMethodBuilder = tb.DefineMethod ("Set" + propertyName,
1750 new Type[] { typeof(string) });
1752 ILGenerator setIL = setMethodBuilder.GetILGenerator ();
1754 setIL.Emit (OpCodes.Ldarg_0);
1755 setIL.Emit (OpCodes.Ldarg_1);
1756 setIL.Emit (OpCodes.Stfld, fieldBuilder);
1757 setIL.Emit (OpCodes.Ret);
1759 // Last, we must map the two methods created above to our PropertyBuilder to
1760 // their corresponding behaviors, "get" and "set" respectively.
1761 propertyBuilder.SetGetMethod (getMethodBuilder);
1762 propertyBuilder.SetSetMethod (setMethodBuilder);
1765 static int handler_called = 0;
1768 public void TestTypeResolve () {
1769 string typeName = genTypeName ();
1771 ResolveEventHandler handler = new ResolveEventHandler (TypeResolve);
1772 AppDomain.CurrentDomain.TypeResolve += handler;
1774 Type t = Type.GetType (typeName);
1775 AssertEquals (typeName, t.Name);
1776 AssertEquals (1, handler_called);
1777 AppDomain.CurrentDomain.TypeResolve -= handler;
1780 Assembly TypeResolve (object sender, ResolveEventArgs args) {
1781 TypeBuilder tb = module.DefineType (args.Name, TypeAttributes.Public);
1788 public void TestIsAssignableTo () {
1789 Type icomparable = typeof (IComparable);
1791 TypeBuilder tb = module.DefineType (genTypeName (),
1792 TypeAttributes.Public, null, new Type[] { icomparable, typeof (Bar) });
1794 Assert ("01", icomparable.IsAssignableFrom (tb));
1795 Assert ("02", !tb.IsAssignableFrom (icomparable));
1797 Assert ("03", typeof (Bar).IsAssignableFrom (tb));
1798 Assert ("04", !typeof (Baz).IsAssignableFrom (tb));
1800 Assert ("05", tb.IsAssignableFrom (tb));
1802 Assert ("06", !tb.IsAssignableFrom (typeof (IDisposable)));
1803 tb.AddInterfaceImplementation (typeof (IDisposable));
1805 // Fails under .net, so we don't support it either
1806 //Assert ("07", tb.IsAssignableFrom (typeof (IDisposable)));
1810 [Category("NotDotNet")]
1811 public void TestIsAssignableTo_NotDotNet () {
1812 Type icomparable = typeof (IComparable);
1814 TypeBuilder tb = module.DefineType (genTypeName (),
1815 TypeAttributes.Public, null, new Type[] { icomparable, typeof (Bar) });
1817 Assert ("01", typeof (Foo).IsAssignableFrom (tb));
1819 tb.AddInterfaceImplementation (typeof (IDisposable));
1822 Assert ("02", typeof (Bar[]).IsAssignableFrom (module.GetType (tb.FullName + "[]")));
1826 [ExpectedException (typeof (InvalidOperationException))]
1827 public void EmptyMethodBody () {
1828 TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
1830 tb.DefineMethod ("foo", MethodAttributes.Public, typeof (void), new Type [] {});
1835 [ExpectedException (typeof (InvalidOperationException))]
1836 public void EmptyCtorBody () {
1837 TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
1839 tb.DefineConstructor (0, CallingConventions.Standard, null);
1845 public void GenericType ()
1847 TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Public);
1848 tb.DefineGenericParameters ("T");
1850 Assert ("01", tb.IsGenericType);
1851 Assert ("02", tb.IsGenericTypeDefinition);
1852 Assert ("03", tb.ContainsGenericParameters);
1853 Assert ("04", !tb.IsGenericParameter);
1855 Type[] args = tb.GetGenericArguments ();
1856 Assert ("a01", !args [0].IsGenericType);
1857 Assert ("a02", !args [0].IsGenericTypeDefinition);
1858 Assert ("a03", args [0].ContainsGenericParameters);
1859 Assert ("a04", args [0].IsGenericParameter);