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?
Interface attributes are by default public , static and final. An interface cannot contain a constructor (as it cannot be used to create objects)
C# Language Attributes Reading an attribute from interface There is no simple way to obtain attributes from an interface, since classes does not inherit attributes from an interface. Whenever implementing an interface or overriding members in a derived class, you need to re-declare the attributes.
Protected members of an interface In general, the protected members can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it. Therefore, the members of an interface cannot be protected.
Yes, you can have all explicit access modifiers like public, private, protected, internal, protected internal for all member types of interface like method, properties, and indexers in C# 8.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With