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?
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.
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.
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.
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. }
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" } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With