Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the usefulness of placing attributes on specific parameters of a method?

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?

like image 913
jpbochi Avatar asked Jun 17 '10 20:06

jpbochi


3 Answers

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

like image 177
Tim Lloyd Avatar answered Sep 29 '22 01:09

Tim Lloyd


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.

like image 35
Philippe Leybaert Avatar answered Sep 29 '22 02:09

Philippe Leybaert


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.

like image 43
Steve Sheldon Avatar answered Sep 29 '22 01:09

Steve Sheldon