Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
like image 238
jens Avatar asked Mar 31 '14 16:03

jens


1 Answers

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.

like image 197
Eric Scherrer Avatar answered Sep 28 '22 17:09

Eric Scherrer