2010-05-19 Jb Evain <jbevain@novell.com>
[mcs.git] / tests / test-295.cs
blobb0bc5d0d9bca6c21e19c2bbb4f1d32baae4057e5
1 using System;
2 using System.Threading;
3 using System.Reflection;
4 using System.Reflection.Emit;
7 [AttributeUsage (AttributeTargets.All)]
8 public class MyAttribute : Attribute {
9 public MyAttribute (object o) {
10 this.o = o;
13 public object my
15 get {
16 return o;
20 object o;
23 public class MyConstructorBuilder
25 public static int Main()
27 Type myHelloworld = MyCreateCallee(Thread.GetDomain());
28 ConstructorInfo myConstructor = myHelloworld.GetConstructor(new Type[]{typeof(String)});
29 object[] myAttributes1 = myConstructor.GetCustomAttributes(true);
30 if (myAttributes1 == null)
31 return 1;
32 if (myAttributes1.Length != 1)
33 return 2;
34 MyAttribute myAttribute = myAttributes1[0] as MyAttribute;
35 if (myAttribute == null)
36 return 3;
37 if (myAttribute.my.GetType() != typeof(TypeCode))
38 return 4;
39 return 0;
42 private static Type MyCreateCallee(AppDomain domain)
44 AssemblyName myAssemblyName = new AssemblyName();
45 myAssemblyName.Name = "EmittedAssembly";
46 // Define a dynamic assembly in the current application domain.
47 AssemblyBuilder myAssembly =
48 domain.DefineDynamicAssembly(myAssemblyName,AssemblyBuilderAccess.Run);
49 // Define a dynamic module in this assembly.
50 ModuleBuilder myModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule");
51 // Construct a 'TypeBuilder' given the name and attributes.
52 TypeBuilder myTypeBuilder = myModuleBuilder.DefineType("HelloWorld",
53 TypeAttributes.Public);
54 // Define a constructor of the dynamic class.
55 ConstructorBuilder myConstructor = myTypeBuilder.DefineConstructor(
56 MethodAttributes.Public, CallingConventions.Standard, new Type[]{typeof(String)});
57 ILGenerator myILGenerator = myConstructor.GetILGenerator();
58 myILGenerator.Emit(OpCodes.Ldstr, "Constructor is invoked");
59 myILGenerator.Emit(OpCodes.Ldarg_1);
60 MethodInfo myMethodInfo =
61 typeof(Console).GetMethod("WriteLine",new Type[]{typeof(string)});
62 myILGenerator.Emit(OpCodes.Call, myMethodInfo);
63 myILGenerator.Emit(OpCodes.Ret);
64 Type myType = typeof(MyAttribute);
65 ConstructorInfo myConstructorInfo = myType.GetConstructor(new Type[]{typeof(object)});
66 try
68 CustomAttributeBuilder methodCABuilder = new CustomAttributeBuilder (myConstructorInfo, new object [] { TypeCode.Double } );
70 myConstructor.SetCustomAttribute(methodCABuilder);
72 catch(ArgumentNullException ex)
74 Console.WriteLine("The following exception has occured : "+ex.Message);
76 catch(Exception ex)
78 Console.WriteLine("The following exception has occured : "+ex.Message);
80 return myTypeBuilder.CreateType();