2

I have two classes, RichString and RequiredRichString. In RequiredRichString, I'm re-implementing the Value property with the 'new' keyword. If I reflect the attributes on Value on RequiredRichString, I only get Required, but after testing posting markup multiple times, AllowHtml is still taking effect.

public class RichString
{
    [AllowHtml]
    public string Value { get; set; }
}

public class RequiredRichString : RichString
{
    [Required]
    new public string Value { get; set; }
}

In short: Why does ASP.NET still acknowledge the AllowHtml attribute when I re-implement the Value property with new?

MStodd
  • 4,716
  • 3
  • 30
  • 50

1 Answers1

1

If you have the flag set:

[AttributeUsage(Inherited=true)]

Then the attribute will be inherited.

But you can subclass the Attribute to your needs, ie MyAttribute(Enabled = true) in the base class and MyAttribute(Enabled = false) in the new implementation. For instance...

[AttributeUsage(Inherited=true, AllowMultiple=true, Inherited=true)]
public class MyAttribute : Attribute
{
    public bool Enabled { get; set; }

    public MyAttribute() { }

    public void SomethingTheAttributeDoes()
    {
        if (this.Enabled) this._DoIt)();
    }
}

public class MyObject
{
    [MyAttribute(Enabled = true)]
    public double SizeOfIndexFinger { get; set; }
}

public class ExtendedObject : MyObject
{
    [MyAttribute(Enabled = false)]
    public new double SizeOfIndexFinger { get; set; }
}

Note this answer: How to hide an inherited property in a class without modifying the inherited class (base class)? - it seems maybe you can achieve what you want by using method overriding rather than hiding.

I can understand why you would think otherwise for a new property, but my understanding is that new is about providing a new implementation, often in the form of a new storage mechanism (a new backing field for instance) rather than changing the visible interface of the subclass. Inherited=true is a promise that subclasses will inherit the Attribute. It makes sense or at least it could be argued that only a superseding Attribute should be able to break this promise.

Community
  • 1
  • 1
tacos_tacos_tacos
  • 10,277
  • 11
  • 73
  • 126