How do I add a custom attribute without a default constructor using mono.cecil
c#, mono.cecil
Solution
First you have to get a reference to the proper version of the constructor:
MethodReference attributeConstructor = module.Import(
typeof(MyAttribute).GetConstructor(new [] { typeof(string), typeof(string) }));
Then you can simply populate the custom attributes with string arguments:
CustomAttribute attribute = new CustomAttribute(attributeConstructor);
attribute.ConstructorArguments.Add(
new CustomAttributeArgument(
module.TypeSystem.String, "Foo"));
attribute.ConstructorArguments.Add(
new CustomAttributeArgument(
module.TypeSystem.String, "Bar"));
Problem
This question is related to this one, but is not a duplicate. Jb posted there that to add a custom attribute, the following snippet would work: ``` ModuleDefinition module = ...; MethodDefinition targetMethod = ...; MethodReference attributeConstructor = module.Import( typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes)); targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor)); module.Write(...); ``` I would like to use something similar, but to add a custom attribute whose constructor takes two string parameters in its (only) constructor, and I'd like to specify values for those (obviously). Can anyone help?