Stef Heyenrath
Stef Heyenrath

Reputation: 9850

Custom Attribute in C# : How to create an Attribute which defines several other Attributes?

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.

Upvotes: 3

Views: 913

Answers (4)

this. __curious_geek
this. __curious_geek

Reputation: 43217

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.

Upvotes: 0

Martin Harris
Martin Harris

Reputation: 28627

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.

Upvotes: 2

Anton Gogolev
Anton Gogolev

Reputation: 115857

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.

Upvotes: 1

Rob Levine
Rob Levine

Reputation: 41338

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.

Upvotes: 2

Related Questions