What does [ something ] mean in c# - c#

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.

Related

A lot of fields with the same attribute

I find myself writing a lot of this kind of stuff:
[SameAttribute]
ClassA fieldA;
[SameAttribute]
ClassB fieldB;
[SameAttribute]
ClassC fieldC;
...
Is there a syntax in C# that would allow me to mark several fields with the same attribute at once? May be there are coding conventions about this situation that would make this code less verbose and more readable?
Edit: Just to clarify, I don't want every field of the class to have this attribute, there's just a lot of them.
No. You will have to apply the [SameAttribute] to each field individually.
If you want SomeAttribute to apply to all fields in a class, it might be possible to apply the attribute to the entire class. However, even if SomeAttribute is allowed to target classes, its exact behavior when doing so is dependent on the implementation of SomeAttribute. Otherwise no, you have to apply the attribute to each field individually.
In addition to the other answers above, PostSharp, which allows "aspect-oriented programming" lets you define attributes that will apply to each member in a class. You can use it to make a custom attribute that would apply your desired attribute to all of the members.
There is nothing out of the box, that I know of, but you could use a Visual Studio add-in like ReSharper to create a live template to automatically add the Attribute you wish to use when you use a certain template
http://www.jetbrains.com/resharper/features/code_templates.html

Custom vs. non-custom attributes?

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)

What's with using C# attributes with the 'Attribute' suffix?

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.

Programmatically add an attribute to a method or parameter

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

Meaning of text between square brackets

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

Categories