ng.
ng.

Reputation: 7189

Parameter attributes in c#

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?

Upvotes: 5

Views: 2558

Answers (2)

Erup
Erup

Reputation: 532

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500835

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.

Upvotes: 13

Related Questions