Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attributes to a base class's properties

Tags:

c#

I have a couple model classes like so:

public class MyModelBase {     public string Name { get; set; } }  public class MyModel : MyModelBase {     public string SomeOtherProperty { get; set; } } 

How can MyModel add a [Required] attribute to the Name property?

like image 435
Mr Bell Avatar asked Jul 01 '11 16:07

Mr Bell


People also ask

Are attributes inherited c#?

The default is false (single-use). The parameter inherited (optional) provides value for the Inherited property of this attribute, a Boolean value. If it is true, the attribute is inherited by derived classes.

Can you inherit attributes?

Subclasses can have two kinds of attributes: local and inherited. A local attribute is one that is defined on the subclass. An inherited attribute is one that is inherited from a parent product class. You customize an inherited attribute domain by editing its definition at the subclass level.

What is an attribute C#?

Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element.


1 Answers

Declare the property in the parent class as virtual:

public class MyModelBase {     public virtual string Name { get; set; } }  public class MyModel : MyModelBase {     [Required]     public override string Name { get; set; }      public string SomeOtherProperty { get; set; } } 

Or you could use a MetadataType to handle the validation (as long as you're talking about DataAnnotations...otherwise you're stuck with the example above):

class MyModelMetadata {     [Required]     public string Name { get; set; }      public string SomeOtherProperty { get; set; } }  [MetadataType(typeof(MyModelMetadata))] public class MyModel : MyModelBase {     public string SomeOtherProperty { get; set; } } 
like image 115
Justin Niessner Avatar answered Oct 06 '22 11:10

Justin Niessner