Search code examples
reflectiontypesattributesreflection.emit

Adding custom attribute to a system class


I want to add classes from System.Activites.Presentation my custom attribute. I tried to do it with emit(TypeBuilder, ModuleBuilder, AssemblyBuilder). Is it possible to change an existing type by adding an attribute to it? Or how to tell TypeBuilder, so that it uses an existing data type? Or inherit from a given type? Thank you.


Solution

  • You can't add attributes to System classes but, if they are not marked as Sealed you can create your custom class deriving from original and adding custom attribute.

    All your code must call derived class, that is identical to the original except on the attribute added.

    [MyAttribute(DisplayName="Name shown")]
    public class MyActivity: System.Activities.Activity
    {
    }
    /// <summary>
    /// Custom attribute definition
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public sealed class MyAttribute : System.Attribute
    {
    
    
        /// <summary>
        /// Defines the attribute
        /// </summary>
             public string DisplayName { get; set; }
        /// <summary>
        /// Allow access to the attribute
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
          public static string GetDisplayName(System.Reflection.MemberInfo prop)
        {
            string field = null;
            object[] attr = prop.GetCustomAttributes(false);
            foreach (object a in attr)
            {
                MyAttribute additional = a as MyAttribute;
                if (additional != null)
                {
                    field = additional.DisplayName;
                }
            }
            return field;
        }
    
    
    }