views:

100

answers:

4

I've the following Attributes defined on my Name field:

[Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(MyResources))]
[Display(Order = 0, Name = ResXStrings.UserName, ResourceType = typeof(MyResources))]
public string Name { get; set; }

I want to create a custom Attribute which looks like this:

[MyAttribute(DisplayName = "Username", ErrorMessage = "ValidationErrorRequiredField", ResourceType = typeof(MyResources))]
public string Name { get; set; }

which defines in code the other two (Required and Display) attributes.

How to implement this ?

UPDATE It's not possible. Thanks to all people who helped answering my question.

+2  A: 

I'm pretty sure you won't be able to do this. The problem is that an attribute is just a bit of metadata attached to a type, a method, a property, etc. It doesn't do anything by itself.

It is up to the code that is consuming the metadata to decide what to do with it and how to act.

Even when an attribute contains some functional code (such as a System.Web.Mvc.ActionFilterAttribute), it is the thing consuming the attribute that invokes it.

In other words, to achieve what you want, you'd have to change the consumers of the attribute to understand your new attribute.

Rob Levine
+1  A: 

There's now way to do this with custom attributes. You can try implementing ICustomTypeDescriptor and add whatever attributes you want, but I doubt that it's supported in each and every scenario.

Anton Gogolev
+2  A: 

I don't think you can. Since consumers of the attributes often find them by type your new attribute would have to be both a RequiredAttribute and a DisplayAttribute. C# doesn't support multiple inheritance so there is no way to make such a class.

Martin Harris
+1  A: 

This is not possible directly but you might be able to do that with some tweaks in design of your application but I'd not recommend doing so because, if you do so you're violating SRP big time by putting two different responsibilities into the same class.

Remember, A class must always have one reason to change.

this. __curious_geek