Access object value from parameter attribute in C#

This is my method

public Component SaveComponent([ValidateMetaFields] Component componentToSave) {
    ...
}

This is my custom attribute:

[AttributeUsage(AttributeTargets.Parameter)]
public class ValidateMetaFieldsAttribute : Attribute
{
    public ValidateMetaFieldsAttribute()
    {
        // how to access `componentToSave` here?
    }
}

I am wondering is there a way to access componentToSave object from ValidateMetaFieldsAttribute? I could not find any sample code or examples.

Jon Skeet
people
quotationmark

No, attribute instances don't have any notion of the target they're applied to.

Note that normally you fetch attributes from a target, so whatever's doing that fetching could potentially supply the information to whatever comes next. Potentially slightly annoying, but hopefully not infeasible.

One small exception to all of this is caller info attributes - if you use something like

[AttributeUsage(AttributeTargets.Parameter)]
public class ValidateMetaFieldsAttribute : Attribute
{
    public ValidateMetaFieldsAttribute([CallerMemberName] string member = null)
    {
        ...
    }
}

... then the compiler will fill in the method name (SaveComponent) in this case, even though the attribute is applied to the parameter. Likewise you can get at the file path and line number.

Given this comment about the purpose, however, I think you've got a bigger problem:

To validate componentToSave and throw an exception before method body even runs.

The code in the attribute constructor will only be executed if the attribute is fetched. It's not executed on each method call, for example. This may well make whatever you're expecting infeasible.

You may want to look into AOP instead, e.g. with PostSharp.

people

See more on this question at Stackoverflow