jens
jens

Reputation: 534

Is it possible to inherit data annotations in C#?

Can I inherit the "password" data annotation in another class?

    public class AccountCredentials : AccountEmail
{
    [Required(ErrorMessage = "xxx.")]
    [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")]
    public string password { get; set; }
}

The other class:

    public class PasswordReset : AccountCredentials
{
    [Required]
    public string resetToken { get; set; }
    **["use the same password annotations here"]**
    public string newPassword { get; set; }
}

I have to use different models due to API call's, but like to avoid having to maintain two definitions for the same field. Thanks!

Addition: something like

[UseAnnotation[AccountCredentials.password]]
public string newPassword { get; set; }

Upvotes: 6

Views: 5164

Answers (2)

Eric Scherrer
Eric Scherrer

Reputation: 3408

Consider favoring composition over inheritance and using the Money Pattern.

    public class AccountEmail { }

    public class AccountCredentials : AccountEmail
    {
        public Password Password { get; set; }
    }

    public class PasswordReset : AccountCredentials
    {
        [Required]
        public string ResetToken { get; set; }

        public Password NewPassword { get; set; }
    }

    public class Password
    {
        [Required(ErrorMessage = "xxx.")]
        [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")]
        public string Value { get; set; }

        public override string ToString()
        {
            return Value;
        }
    }

Perhaps it has become a golden hammer for me, but recently I have had a lot of success with this, especially when given the choice between creating a base class or instead taking that shared behavior and encapsulating it in an object. Inheritance can get out of control rather quickly.

Upvotes: 6

cat916
cat916

Reputation: 1361

In the base class, you can make it virtual property, and change it override in the derived class. However, it would not inherit attribute, we do a tricky here :

public class AccountCredentials : AccountEmail
{
 [Required(ErrorMessage = "xxx.")]
 [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")]
 public virtual string password { get; set; }
}

public class PasswordReset : AccountCredentials
{
 [Required]
 public string resetToken { get; set; }
 public override string password { get; set; }
}

Upvotes: 2

Related Questions