Something which implements the ICustomAttributeProvider interface will allow you to get custom attributes that have been applied to it via the GetCustomAttributes method. As I understand it, a custom attribute is basically a special class (ending in "Attribute" and extending the Attribute class) that is created to be applied to something like a method or class using the appropriate syntax ([FooAttribute] just before the method/class/etc. in C#, for example). But if that is a custom attribute, what is a non-custom attribute? I used to think that attributes that were bundled with .NET were non-custom, but GetCustomAttributes even returns me attributes like System.ThreadStaticAttribute, which are very core to the .NET framework.
Is there such a thing as a non-custom attribute, or is "custom attribute" just a tautology?
Everything that derives from Attribute is a custom attribute.
"Attribute" is a generic term. Objects in the real world have innumerable attributes. Classes, members and parameters all have attributes that we can describe -- names, types, accessors, number of members, inheritance information, etc.
Custom attributes are things that we tack on -- aspects that we want to associate and use to describe, but which are not intrinsic.
I don't know if the following has any relevance, but if you say
var a = typeof(string).Attributes;
you get a value of a flags enum type called TypeAttributes. Maybe these flags are the "non-custom" attributes of the type?
See Wikipedia, quoting:
Developers can add metadata to their code through attributes. There
are two types of attributes, custom and pseudo custom attributes, and
to the developer these have the same syntax. Attributes in code are
messages to the compiler to generate metadata. In CIL, metadata such
as inheritance modifiers, scope modifiers, and almost anything that
isn't either opcodes or streams, are also referred to as attributes.
See also the CLI specification about extending metadata, where references are found to the term "custom" attributes (e.g. I.9.7 in http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf)
Related
Are there any conventions (perhaps by Microsoft) on attributes if their name should be singular or plural?
I'm not sure what the naming conventations are or if there are any at all? I want an attribute for the roles in my system I'm not sure whether by convention (if any) I should pluralize it to RolesAttribute or keep it singular RoleAttribute.
- Edit -
Now I think of it custom attributes are still classes that derive from the Attribute base class, so would the conventions of classes apply to C# attributes as well?
It really depends on the functionality you are implementing. In short, if you are assigning one role using your attribute then keep it singular, if you are assigning multiple roles then make it plural.
In more general terms, Attributes should be named using clear pascal cased names and their function is to associate metadata, or declarative information with code. As with everything else in your code, make sure that they are descriptive and unambiguous.
Some good guidelines I like to follow are the following:
Avoid unsealed attributes
Custom attributes should end with the suffix Attribute
Define constructors which have parameters to intialize properties corresponding to the required arguments
Each constructor parameter should have the same name (apart from the casing) as the corresponding property
Define accessors for attribute parameters, usually settable properties for optional parameters and getter only for required parameters
Mark attributes with the AttributeUsageAttribute
I have seen that in some cases we use following syntax format in c#,
[something]
void methodM(){
}
Example :
[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}
[WebMethod]
public void MyWebMethod(){/* code */}
How this works at the compilation?
Explanation
Those are attributes or annotations. They are kind of metadata for the member they are placed on.
For example, using MethodImpl attribute, you can specify the details of how a method is implemented. And using WebMethod attribute, you mark that method as a web service method.
Further reading:
Attributes (C# Programming Guide)
Attributes in C#
[something] is an attribute. The attributes are stored in the metadata of the assembly and can be read with reflection. This is frequently used by libraries and frameworks to control behavior. Some attributes, like ObsoleteAttribute control compile time behavior, but most affect run time behavior. You can create your own attributes by inheriting from Attribute.
These are Attributes [something], which are descriptive tags that can be used to provide additional information about types (classes),
members, and properties. Attributes can be used by .NET to decide how to handle objects while an application is running.
I'm looking at some C# code that applies several LINQ to SQL attributes with the Attribute suffix, e.g. ColumnAttribute, instead of the plain Column that I am used to using. Is there any reason but verbosity to do this?
There is no semantic difference. Probably whoever wrote the code just preferred that notation.
It's also possible that the code was automatically generated using a tool. Code generation tools usually don't bother to strip the Attribute bit from the attribute's type name.
Most attributes end with the word Attribute, including ColumnAttribute, CLSCompliantAttribute, and SerializableAttribute. The compiler allows the last word Attribute to be omitted. It's the programmer's choice whether to add Attribute to such names or not.
The Attribute suffix, however, is merely a convention: it is perfectly valid, albeit unusual, to define an attribute, for example, as follows:
[AttributeUsage(AttributeTargets.All)]
public class Foo : Attribute {
}
just as it is to define an exception named Throwable, for example.
The attribute is called ColumnAttribute. The compiler just provides syntactic-sugar to allow you to specify them without the Attribute suffix.
There's no practical difference.
No, it's just a style decision. However, if what you're looking at is code generated using CodeDOM the presence of the suffix is expected since C# code generator will keep the full ___Attribute type name when adding an attribute.
They're syntactically the same. AFAIK there's no reason to do this unless the person in question wasn't familiar with the fact that syntax sugar in C# adds the 'Attribute' suffix automatically when adding an attribute via square brackets.
Column is simply the nickname of ColumnAttribute, and syntactically identical in functionality, and allowed by the compiler in either form.
Some people prefer to use the full name, out of habit of following the Framework Naming Guidelines, which encourage adding Attribute to custom attribute classes, or I to interface types.
If you look at the Philips Healthcare - C# Coding Standard, rule 3#122, you can see they actually want coders to add the suffix "Attribute" to attributes.
http://www.tiobe.com/content/paperinfo/gemrcsharpcs.pdf
The code may be generated but the author(s) of the code generator are probably trying to create code that meets as many standards as possible.
I can use TypeDescriptor.AddAttributes to add an attribute to a type in runtime. How do I do the same for a method and parameter? (maybe 2 separate questions...)
TypeDescriptor.AddAttributes only affects a very specific use-case; i.e. from within System.ComponentModel. For the rest of reflection, it knows nothing about the extra attribute. And indeed, System.ComponentModel doesn't really apply to methods or parameters.
So in short; you can't. You will need to store this information somewhere else (bespoke), or add it at compile-time.
As I see from analyzing the TypeDescriptor class in Reflector, the .AddAttributes method internally calls the .AddProvider method. The TypeDescriptionProvider instance passed to it is actually responsible for providing meta-data. You could try adding the [TypeDescriptionProviderAttribute] attribute to your class and implement your own provider by deriving from the TypeDescriptionProvider class. As the documentation says, by overriding TypeDescriptionProvider.CreateInstance, you could provide a substitute object whose type has all necessary attributes. I suspect that the attributes applied to methods inside the substitution type will also take effect. However, I haven't tried that myself, so feel free to experiment...
I have seen a lot of C# programs that use the [], for example [STAThread] and then the code follows. Another classic example is [DLLImport].
I know what STAThread means but my question is what is the significance of the square brackets, essentially what do they tell the compiler?
It's an attribute. Attributes are a form of metadata that you can attach to various code elements: classes, methods, assemblies etc.
Some attributes have special meaning to the C# compiler, for instance the [Serializable] probably tells the compiler to emit some code that can serialize an instance of the class (I say 'probably' since I do not know the inner workings of the C# compiler).
You can also create your own attributes (by inheriting System.Attribute). Using reflection you could then at run-time extract information from the attributes.
A simple example would be to create an attribute to specify what kind of input field to use in a HTML form when displaying an object's property.
Some links:
Book chapter on attributes
Attributes overview (MSDN)
https://stackoverflow.com/search?q=C%23+attributes
http://www.google.com/search?q=C%23+attributes
These are attributes.
Attributes have many uses - [Obsolete] marks a method as obsolete and the compiler will warn you. Others like [DebuggerNonUserCode] tell nothing to the compiler and are there to let the debugger know that the code in the marked method is auto-generated.
You can also create your own attributes and use them to mark any kind of metadata. For example, your Customer object might have an attribute [MarketingInformation("Customer is rich! Milk him good!")].
See here for info about attributes in .Net:
http://msdn.microsoft.com/en-us/library/5x6cd29c.aspx
They are attributes, that add meta data to whatever they are decorating.
Theses are called code attributes. Attributes are used to mark code with properties which are usually designed to specify behavior during execution. They are commonly used to mark methods, properties and parameters. During execution of your code something called "reflection" will be performed to examine the code. Reflection tells the compiler to observe and obey any instructions specified by you as the coder marking attributes against the code.
A good example would be the [Serializable] attribute. This attribute when marked above a class indicates to the compiler that it can be serialized for the purposes of persisting the class instance or for transmitting across a medium such as SOAP web services.
See the following article:
link text