Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Override an attribute in a subclass

Tags:

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!

like image 673
Mike Blandford Avatar asked Oct 01 '10 14:10

Mike Blandford


2 Answers

This is exactly why framework attributes that can be "overriden", take a boolean parameter which (on the face of it) seems pointless. Take BrowsableAttribute for example; the boolean parameter would seem to be obsolete judging by the name, but take this example:

class SomeComponent {   [Browsable(true)]   public virtual string SomeInfo{get;set;} }  class SomeOtherComponent : SomeComponent {   [Browsable(false)]  // this property should not be browsable any more   public override string SomeInfo{get;set;} } 

so, to answer your question, you could make your ExternallyVisible attribute take a boolean parameter, to indicate whether it is actually externally visible, and when you inherit you can change to false - just like BrowsableAttribute.

like image 149
Jamiec Avatar answered Sep 18 '22 02:09

Jamiec


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(); } 
like image 23
Chris Martin Avatar answered Sep 22 '22 02:09

Chris Martin