views:

226

answers:

2

How can I do the following with c# attributes. Below is a snippet of Java that annotates parameters in a constructor.

public class Factory {
    private final String name;
    private final String value;
    public Factory(@Inject("name") String name, @Inject("value") String value) {
        this.name = name;
        this.value = value;
    }
}

From looking at c# annotations it does not look like I can annotate parameters. Is this possible?

+7  A: 

You can absolutely attribute parameters:

public Factory([Inject("name")] String name, [Inject("value")] String value)

Of course the attribute has to be declared to permit it to be specified for parameters via AttributeUsageAttribute(AttributeTargets.Parameter).

See OutAttribute and DefaultParameterValueAttribute as examples.

Jon Skeet
I was just typing this out! You're too fast for me =D
Tejs
A: 

Create an attribute class with AttributeUsageAttribute and them, use Reflection to inspect the parameters.

[System.AttributeUsage(System.AttributeTargets.All)]
class NewAttribute : System.Attribute { }

Accessing Attributes with Reflection

Erup