Here's how to set the Named Parameters of a custom attribute that completely bypasses setting the attribute value using its constructors. As a note, you cannot set the CustomAttributeNamedArgument.Argument.Value parameter or even the CustomAttributeNamedArgument.Argument parameter directly, as they are readonly.
The following is equivalent to setting - [XXX(SomeNamedProperty = {some value})]
var attribDefaultCtorRef = type.Module.Import(typeof(XXXAttribute).GetConstructor(Type.EmptyTypes)); var attrib = new CustomAttribute(attribDefaultCtorRef); var namedPropertyTypeRef = type.Module.Import(typeof(YYY)); attrib.Properties.Add(new CustomAttributeNamedArgument("SomeNamedProperty", new CustomAttributeArgument(namedPropertyTypeRef, {some value}))); method.CustomAttributes.Add(attrib);
Rohit source share