Skip to content

The ConstructorBuilder and MethodBuilder generated parameter should not has default value by default. #20909

@edwardmeng

Description

@edwardmeng

The HasDefaultValue of parameters should be false by default, for the constructors and methods generated from System.Reflection.Emit.ConstructorBuilder and System.Reflection.Emit.MethodBuilder. But actually the HasDefaultValue of the parameters are true. It means the emitter generates parameter default values as null unexpected. The sample code as following:

var builder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicProxyGenAssembly"), AssemblyBuilderAccess.Run).DefineDynamicModule("DynamicProxyGenAssembly");
var type = builder.DefineType("MyProxy", TypeAttributes.Public);

var constructorBuilder = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] {typeof(Version)});
var il = constructorBuilder.GetILGenerator();
il.Emit(OpCodes.Ret);

var methodBuilder = type.DefineMethod("DoSomething", MethodAttributes.Public, CallingConventions.Standard, typeof(void),new[] {typeof(Version)});
il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ret);

var typeInfo = type.CreateTypeInfo();
var constructor = typeInfo.GetConstructor(new[] {typeof(Version) });
var parameters = constructor.GetParameters();
Assert.False(parameters[0].HasDefaultValue);  // Fails

var method = typeInfo.GetMethod("DoSomething", new[] {typeof(Version)});
parameters = method.GetParameters();
Assert.False(parameters[0].HasDefaultValue); // Fails

But the DynamicMethod has the correct parameter default value as expected. The sample code as following:

var method = new DynamicMethod("x", typeof(void), new [] { typeof(Version) });
var il = method.GetILGenerator();
il.Emit(OpCodes.Ret);
var delegateMethod = method.CreateDelegate(typeof(Action<Version>));
var parameters = delegateMethod.GetMethodInfo().GetParameters();
Assert.False(parameters[0].HasDefaultValue); // Success

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Reflection.Emitbuggood first issueIssue should be easy to implement, good for first-time contributorshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions