Sam Jones
Sam Jones

Reputation: 4618

Creating a parameterless property attribute c#

I'm trying to create an attribute which reads a string property, does some work and replaces it.

How can i access the property from the attribute?

Attribute:

[AttributeUsage(AttributeTargets.Property)]
public class CustomAttribute : Attribute
{
    public CustomAttribute()
    {
        //get the property value
        //propertyValue = propertyValue + "!";
        //set the property value to be the updated propertyValue;

        //how do i get the value of the property the attribute is added to and modify it?
    }
}

Usage:

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

Upvotes: 1

Views: 529

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062770

Attributes don't do anything. They are metadata - they aren't active unless you query the metadata for the attribute model, or you're using certain IL rewriting tools. Note that an attribute doesn't have direct access to the context upon which it resides - for that, you'd need to add methods to your attribute, and invoke those methods on the materialized attribute, passing in any required context.

An object instance of an attribute is only created when you ask for that via the reflection APIs (and: it gives you an entirely different instance every time you query). Until then, it just exists as metadata.

Upvotes: 3

Related Questions