tags:

views:

126

answers:

3

I wonder if you can help me with this.

I'm reading up about attributes and understand that they can be made to apply to different target entities with you code - (see Attribute Targets).

So, looking at the AssemblyInfo.cs file in my project, I can see the following:

[assembly: AssemblyTitle("AttributesDemo")]
[assembly: AssemblyDescription("")]

Which makes sense to me. An attribute whose target is the assembly.

In my code I can add an attribute on a class as follows:

[MyAttribute]
class MySerialzableClass
{

With MyAttribute being:

[AttributeUsage (AttributeTargets.All)]
public class MyAttribute : System.Attribute
{
}

So, I got to thinking about the assembly: statement in the first code block. And tried this, just for experimentation:

[class: MyAttribute]
class MySerialzableClass
{

This gives the compiler warning:

'class' is not a recognized attribute location. All attributes in this block will be ignored.

So my question is this - Why do have to specify the Attribute Target on some attributes and are not requried, or permitted to for others? Moreover, for which ones must you do this?

You help would be appreciated. Thanks.

+3  A: 

Normally, the attribute comes right before what it affects, such as the class or method. For assembly-wide attributes, there's no "before", so you have to specify.

Steven Sudit
+4  A: 

you have to specify target explicitly in case where the target is not represented in code. I know only three that targets, assembly, module and return:

[return: MyAttribute]
public static int meth(

for class specifying class: is excessive, compiler can understand what do you meant

Andrey
+1 for mentioning the *other* exception.
Steven Sudit
+1 and accepted answer, although shouldn't it be 'ReturnValue:', not 'Return:'
James Wiseman
no :) just write and try to compile.
Andrey