Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get member to which attribute was applied from inside attribute constructor?

Tags:

I have a custom attribute, inside the constructor of my custom attribute I want to set the value of a property of my attribute to the type of the property my attribute was applied to, is there someway to access the member that the attribute was applied to from inside my attribute class?

like image 459
ryudice Avatar asked Feb 19 '10 20:02

ryudice


People also ask

Which method is used to retrieve the values of the attributes?

First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you can use its properties to get the values.

How to determine attribute in C#?

By using reflection, you can retrieve the information that was defined with custom attributes. The key method is GetCustomAttributes , which returns an array of objects that are the run-time equivalents of the source code attributes.

Are attributes inherited C#?

In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code.

How to Get a class attribute C#?

In C#, you specify an attribute by placing the name of the attribute enclosed in square brackets ([]) above the declaration of the entity to which it applies. [Serializable] public class SampleClass { // Objects of this type can be serialized. }


2 Answers

It's possible from .NET 4.5 using CallerMemberName:

[SomethingCustom] public string MyProperty { get; set; } 

Then your attribute:

[AttributeUsage(AttributeTargets.Property)] public class SomethingCustomAttribute : Attribute {     public StartupArgumentAttribute([CallerMemberName] string propName = null)     {         // propName == "MyProperty"     } } 
like image 163
Niels Filter Avatar answered Sep 23 '22 17:09

Niels Filter


Attributes don't work that way, I'm afraid. They are merely "markers", attached to objects, but unable to interact with them.

Attributes themselves should usually be devoid of behaviour, simply containing meta-data for the type they are attached to. Any behaviour associated with an attribute should be provided by another class which looks for the presence of the attribute and performs a task.

If you are interested in the type the attribute is applied to, that information will be available at the same time you are reflecting to obtain the attribute.

like image 44
Paul Turner Avatar answered Sep 26 '22 17:09

Paul Turner