The following code creates an assembly called MyAssembly.dll which contains a single interface called IMyType. IMyType has a single property called my property.
string assemblyName = "MyAssembly";
AssemblyBuilder assemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName(assemblyName),
AssemblyBuilderAccess.RunAndSave
);
ModuleBuilder moduleBuilder =
assemblyBuilder.DefineDynamicModule(
assemblyName,
$"{assemblyName}.dll",
true
);
TypeBuilder typeBuilder =
moduleBuilder.DefineType(
$"{assemblyName}.IMyType",
TypeAttributes.Public |
TypeAttributes.Interface |
TypeAttributes.Abstract
);
PropertyBuilder propertyBuilder =
typeBuilder.DefineProperty(
"MyProperty",
System.Reflection.PropertyAttributes.HasDefault |
System.Reflection.PropertyAttributes.SpecialName,
typeof(int),
null
);
MethodBuilder getBuilder =
typeBuilder.DefineMethod(
"get_MyProperty",
MethodAttributes.Virtual |
MethodAttributes.Abstract |
MethodAttributes.SpecialName,
typeof(int),
Type.EmptyTypes
);
MethodBuilder setBuilder =
typeBuilder.DefineMethod(
"set_MyProperty",
MethodAttributes.Virtual |
MethodAttributes.Abstract |
MethodAttributes.SpecialName,
typeof(int),
Type.EmptyTypes
);
propertyBuilder.SetGetMethod(getBuilder);
propertyBuilder.SetSetMethod(setBuilder);
typeBuilder.CreateType();
assemblyBuilder.Save($"{assemblyName}.dll");
When I decompile the assembly in DotPeek I see the code I expect to see:
In another project however that references this assembly I create a class that implements my new IMyType and visual studio creates this:
What do I need to do so that visual studio will see this as an auto property instead of two methods?
Probably, you should define your set
method as void and taking one argument of type int.
MethodBuilder setBuilder =
typeBuilder.DefineMethod(
"set_MyProperty",
MethodAttributes.Virtual |
MethodAttributes.Abstract |
MethodAttributes.SpecialName,
typeof(void),
new[] { typeof(int) }
);