views:

68

answers:

5

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?

+1  A: 

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.

Steve Sheldon
Indeed, the question can be considered subjective in the sense that there's no "right" answer. There are some answers that are better than others, however.
jpbochi
Doesn't Code Contracts use this extensively?
JBRWilkinson
+2  A: 

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.

Philippe Leybaert
+4  A: 

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".

chibacity
+1  A: 

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.

justin.m.chase
interesting, but I think it's a different mechanism altogether...
flq
A: 

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) {
    ...
  }
}
flq