Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
ng. Avatar asked Apr 27 '10 12:04

ng.


2 Answers

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.

like image 149
Jon Skeet Avatar answered Oct 13 '22 10:10

Jon Skeet


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

like image 28
Erup Avatar answered Oct 13 '22 10:10

Erup