Lets say I have these class
public class BaseClass
{
public int Id { get; set; }
}
and
public class SomeClass : BaseClass
{
... more properties ...
}
BaseClass is considered to be used on a lot of places.
In my case I’m using ASP.NET MVC 3’s EditorForModel to render Views, and it’s common to decorate properties with attributes such as [Display(Name = "Id"), Required]
But lets say I would want to decorate the properties of BaseClass in different ways for every class that inherits it. In SomeClass I may want to decorate Id with [Required] and in OtherClass I might want to decorate it with [SomeCustomAttribute].
Is there a way to this?
It would be nice to be able to do something like this:
public class SomeClass : BaseClass
{
public SomeClass()
{
WithProperty(x => x.Id).AddAttribute(new RequiredAttribute());
...
}
... more properties ...
}
Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren’t first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they’re writable but that won’t affect the attribute as it is applied to the type