Attribute on Interface members does not work

annotations, attributes, c#, interface

Solution

Attributes on interface properties doesn't get inherited to the class, you may make your interface an Abstract Class.

Found an answer from Microsoft:

The product team does not want to implement this feature, for two main reasons:

- Consistency with DataAnnotations.Validator

- Consistency with validation behavior in ASP.Net MVC

- tricky scenario: a class implements two interfaces that have the same property, but with conflicting attributes on them. Which attribute would take precedence?

Problem

In my application several models need `Password` properties (eg, `Registration` and `ChangePassword` models). The `Password` property has attribute like `DataType` and `Required`. Therefore to ensure of re-usability an consistency, I created : ``` interface IPasswordContainer{ [Required(ErrorMessage = "Please specify your password")] [DataType(DataType.Password)] string Password { get; set; } } ``` And ``` class RegistrationModel : IPasswordContainer { public string Password { get; set; } } ``` Unfortunately, the attributes does not work. Then I tried changing the interface to a class: ``` public class PasswordContainer { [Required(ErrorMessage = "Please specify your password")] [DataType(DataType.Password)] public virtual string Password { get; set; } } ``` And ``` public class RegistrationModel : PasswordContainer { public override string Password { get; set; } } ``` Now it is working. Why it is so? Why the attributes are working when inherited from class but not working when inherited from interface?

Original source

Related problems