Tomtom
Tomtom

Reputation: 9394

Get propertyname where attribute is on

In my application I have a custom attribute calles ResourceTargetAttribute which looks like:

[AttributeUsage(AttributeTargets.Property)]
private class ResourceTargetAttribute : Attribute
{
    public ResourceTargetAttribute(string resourceKey)
    {
        ResourceKey = resourceKey;
    }

    public string ResourceKey { get; private set; }
}

The usage looks like:

[ResourceTarget("FileNotFoundErrorText")
public string FileNotFoundErrorText { get; private set; }

The constructor of the class where the FileNotFoundErrorText-Property is defined resolves this attribute. This just works fine.

Now I was thinking about to extend the attribute to have a parameterless constructor and if this is called the name of the Property the attribute is on will automatically be used for the ResourceKey. Therefore I've introduced a new constructor which just looks like:

public ResourceTargetAttribute()
{

}

And the usage then should look like:

[ResourceTarget()]
public string FileNotFoundErrorText { get; private set; }

And here I want to have name of the FileNotFoundErrorText-Property automatically be passed to the ResourceTarget-Attribute.

Is there a possibility to do this?

Upvotes: 1

Views: 80

Answers (2)

Serraniel
Serraniel

Reputation: 296

The CallerMemberNameAttribute might help you:

public ResourceTargetAttribute([CallerMemberName] string propertyName = null)
{
  ResourceKey = propertyName;
}

Usage:

[ResourceTarget]
public string FileNotFoundErrorText { get; private set; }

If you get the attribute, the

attr.ResourceKey

property should contain FileNotFoundErrorText as value.

Otherwise I just would go the way passing the name as string as attributes are metadata applied to the members of a type, the type itself, method parameters or the assembly so you must have the original member itself to access its meta data.

Upvotes: 1

earloc
earloc

Reputation: 2090

The easiest way would be to utilize nameof-operator:

[ResourceTarget(nameof(FileNotFoundErrorText)]
public string FileNotFoundErrorText { get; private set; }

Another approach would be to modify the code that actual examines / searches for these marker-attributes. use reflection to get the actual Property-Name on which the attribute was applied.

Maybe if you provide the mentioned "constructor-code" I could further assist.

Upvotes: 0

Related Questions