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?
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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With