0

I have been working on a problem in MVC where I was facing code duplicity issue creating View-Models. I was wondering if there is a way to create a class whose properties can refer to properties defined in another class. I just need to write the property name or just the reference. I basically need all other stuff like Annotations should automatically come over to my new class definition.

Here is what I am looking for:

let say I have a Class A having some annotations.

Class A {

        [Required]
        [EmailAddress]
        [Display(Name = "Email ID")]
        public string EmailID { get; set; }
        [Required]

        [Required]
        [Display(Name = "Name")]
        public string FName { get; set; }
}

Now I need to write a new class B referring to some properties defined in class A.

Class B {
    public string EmailID; //should refer to class B so that I don't have to write annotations again
    public string newproperty;
}
Munendra
  • 33
  • 6

1 Answers1

3

You are expecting something that isn't there. There is only one way to indicate that some property of B is 'the same' as that of A, and that is inheritance.

If you make B derive from A, it inherits the property EmailID and its annotations.

Another option is to use annotations on interfaces, but those share the same problems as deriving in my opinion.

Else, you just have to copy/paste the annotation, since there isn't any obvious relationship except that they share the same name.

Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Yes I knew there is no such solution but I thought I should put my question... it was out of curiosity really. – Munendra May 05 '15 at 09:21