Search code examples
c#mono.cecilfody

Get named values from a Fody CustomAttribute Constructor


Can anyone tell me how to read the property assignments of a CustomAttribute's constructor

[Display(Name = "This name and value")]

They don't seem to appear in either theattribute.ConstructorArguments or theAttribute.Properties (which is always empty).


Solution

  • private CustomAttribute CloneAttribute(CustomAttribute sourceAttribute)
    {
        MethodReference sourceAttributeConstructor = sourceAttribute.Constructor;
        MethodReference localAttributeConstructorReference = ModuleDefinition.ImportReference(sourceAttributeConstructor);
    
        var localCustomAttribute = new CustomAttribute(localAttributeConstructorReference);
        foreach (var sourceAttributeConstructorArgument in sourceAttribute.ConstructorArguments)
        {
            TypeReference localAttributeTypeReference = sourceAttributeConstructorArgument.Type;
            CustomAttributeArgument localAttributeInstance = new CustomAttributeArgument(localAttributeTypeReference, sourceAttributeConstructorArgument.Value);
            localCustomAttribute.ConstructorArguments.Add(localAttributeInstance);
        }
    
        // This was the piece of missing code
        foreach(var sourceAttributePropertArgument in sourceAttribute.Properties)
        {
            var localAttributePropertyArgument = new CustomAttributeNamedArgument(name: sourceAttributePropertArgument.Name, argument: sourceAttributePropertArgument.Argument);
            localCustomAttribute.Properties.Add(localAttributePropertyArgument);
        }
    
        return localCustomAttribute;
    }