tags:

views:

285

answers:

5

Hi,
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 STATThread means but my question is what is the significance of the square brackets, essentially what do they tell the compiler.

Many Thanks

+7  A: 

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 determine what kind of input field to use in a HTML form when displaying an object's property.

Some links:

codeape
+1  A: 

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!")].

Sander
A: 

See here for info about attributes in .Net:

http://msdn.microsoft.com/en-us/library/5x6cd29c.aspx

Brian
A: 

They are attributes, that add meta data to whatever they are decorating.

Brian Rasmussen
A: 

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