Reputation: 4406
I'm looking for a list of reasonable use cases of putting attributes in a parameter.
I can think of some good cases for attributes in a method, but can't seem to see a good usage of a parameter attribute. Please, enlighten me.
And what about attributes on the return type of a method?
Upvotes: 5
Views: 1520
Reputation: 171914
For example, in Vici MVC, a .NET MVC framework, the parameters of a controller's action method can be "mapped" to a parameter with a different name. This is how it's done in in Vici MVC:
public void ActionMethod([Parameter("user")] int userId)
{
}
This will map the parameter "user" from the query string to the parameter userId.
That's just a simple example on how you can use attributes for parameters.
Upvotes: 3
Reputation: 38494
A specific case where they are used is in PInvoke. Parameters in PInvoke signatures can be optionally decorated with additional information through the use of attributes so that PInvoke marshalling of individual arguments can be either explicitly specified or have the default marshalling behaviour overriden, e.g.:
[DllImport("yay.dll")]
public static extern int Bling([MarshalAs(UnmanagedType.LPStr)] string woo);
This overrides the default marshalling behaviour for the string argument "woo".
Upvotes: 7
Reputation: 22859
As others have shown, what a thing is good for can be answered by what other people do with it. E.g.in MEF you can use it on the parameter of a constructor to specify that you want to import a dependency with a certain name:
public class Foo {
[ImportingConstructor]
public Foo([Import("main")] Bar bar) {
...
}
}
Upvotes: 0
Reputation: 13685
In Boo you can add macro attributes. Such as:
def Foo([required]p):
pass
This tells the compiler to transform the Foo method into this:
def Foo(p):
raise ArgumentNullException("p") if p is null
Slightly different than the static examples but interesting nonetheless.
Upvotes: 1
Reputation: 6651
When using reflection, you might want some metadata associated with a property, for example, if you were to perform some code generation based on the properties in a class.
I would say that this question is a little open ended, there will be a time sooner or later that a need will arise and you will be thankful that the language supports it.
Upvotes: 1