Search code examples
c#postsharpmono.cecil

Replace Attribute constructor arguments with mono.cecil or postsharp


I have an example method definition:

[FooAttribute("One","time")]
public void Bar(){}

Is it possible through one of the above techniques to change, for example, the argument "one" to "two" ?


Solution

  • Assuming the following attribute and class:

    public class MyAttribute : Attribute
    {
        public MyAttribute(string a, string b)
        {
            this.a = a;
            this.b = b;
        }
        private string a,b;
    }
    
    [My("foo", "bar")]
    class WithAttribute
    {
    }
    

    You can use some code similar to the following (remember, this code is only for demonstration purposes and it assumes a lot of things and do no error handling at all)

    var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
    var type = assembly.MainModule.Types.Where(t => t.Name.Contains("WithAttribute")).Single();
    
    var attr = type.CustomAttributes.Where(ca => ca.AttributeType.FullName.Contains("MyAttribute")).Single();
    
    type.CustomAttributes.Remove(attr);
    
    var newAttr = new CustomAttribute(attr.Constructor)
    { 
        ConstructorArguments = 
        {
            new CustomAttributeArgument(
                 attr.ConstructorArguments[0].Type, 
                 attr.ConstructorArguments[0].Value + "-Appended"),
    
            new CustomAttributeArgument(
                 attr.ConstructorArguments[1].Type, 
                 attr.ConstructorArguments[1].Value)
         }
    };
    
    type.CustomAttributes.Add(newAttr);
    
    assembly.Write(path);