Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute on Interface members does not work

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?

like image 928
Mohayemin Avatar asked Aug 24 '12 09:08

Mohayemin


People also ask

Can we have attributes in interface?

Interface attributes are by default public , static and final. An interface cannot contain a constructor (as it cannot be used to create objects)

CAN interfaces have attributes C#?

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.

Can we define protected members in interface?

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.

Can we use protected in interface C#?

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.


1 Answers

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?
like image 191
Habib Avatar answered Sep 22 '22 13:09

Habib