Bridget the Midget
Bridget the Midget

Reputation: 201

Decorate properties with attributes in a more flexible manner

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 ...
}

Upvotes: 1

Views: 1784

Answers (3)

phoog
phoog

Reputation: 43036

You can declare the property as virtual, and override it in the derived class. Decorate the override with the class-specific attributes, and the base property with any attributes that should apply to all classes.

Be sure that attributes applied to base properties are not themselves decorated with the AttributeUsageAttribute with an Inherited value of false (the default is true). If an attribute's AttributeUsage specifies Inherited == false then an overriding property will not inherit the attribute. See the documentation for more information.

Upvotes: 2

Cinchoo
Cinchoo

Reputation: 6322

It is not possible to decorate the attributes to members for individual object instance level. It is type specific meta-data. If you really need this, you will have to implement your own attribute management dealing with instance specific.

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56429

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

Upvotes: 3

Related Questions