C# Override an attribute in a subclass

attributes, c#

Solution

It works for me.

Test code:

public static void Main()
{
    var attribute = GetAttribute(typeof (MyWebControl), "StyleString", false);
    Debug.Assert(attribute != null);

    attribute = GetAttribute(typeof(SmarterWebControl), "StyleString", false);
    Debug.Assert(attribute == null);

    attribute = GetAttribute(typeof(SmarterWebControl), "StyleString", true);
    Debug.Assert(attribute == null);
}

private static ExternallyVisibleAttribute GetAttribute(Type type, string propertyName, bool inherit)
{
    PropertyInfo property = type.GetProperties().Where(p=>p.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

    var list = property.GetCustomAttributes(typeof(ExternallyVisibleAttribute), inherit).Select(o => (ExternallyVisibleAttribute)o);

    return list.FirstOrDefault();
}

Problem

``` public class MyWebControl { [ExternallyVisible] public string StyleString {get;set;} } public class SmarterWebControl : MyWebControl { [ExternallyVisible] public string CssName{get;set;} new public string StyleString {get;set;} //Doesn't work } ``` Is it possible to remove the attribute in the subclass? I do want the attribute to get inherited by other subclasses, just not this one. Edit: Whoops, looks like I forgot to compile or something because the code as posted above does, in fact, work!

Original source