views:

223

answers:

7
  • What is the purpose of Attributes in C#?

  • How do I know which attribute have to use for particular functionality?

  • How can I add them dynamically in c#?

  • What are custom attributes ?

+3  A: 

Attributes are used for a Declarative Programming Model.

Attributes don't force any functionality (unless out of the box). For out-of the box attributes read up the documentation on msdn. For your own attributes you need to write code on what do if a class/method etc. has an attribute.

I don't think attributes are added dynamically. They're read dynamically though. They are metadata so are added at compile-time. Check this: http://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c

Custom attributes are those that you create and tag your classes with. To create an attribute you need to create a class (for the attribute) that inherits from System.Attribute. Check this: http://msdn.microsoft.com/en-us/library/sw480ze8.aspx

Sidharth Panwar
+5  A: 
  1. Attributes are meant to add additional information about a class, function, etc. Compilers sometimes do special things when they see an attribute. Other attributes are looked at by libraries while the program is running.

  2. Start by looking at the documentation for the functionality you want. It should list what attributes are necessary.

  3. No. Attributes can only be applied before the code is compiled.

  4. That is just an attribute you created yourself as opposed to one that came with .NET.

Jonathan Allen
+1  A: 

Attributes are used to provide meta data about your classes and methods, properties, and events inside your classes.

Some of the most common attributes are used to tell the Designer information about properties in classes, such as Browsable and Description. This meta-data is then used by the PropertyGrid. Other examples of attributes would be the Serializable or Obsolete attributes used during serialization or to mark code elements as obsolete.

You can add attributes to classes, properties, methods, and events by using the [AttributeName(parameter1,...)] syntax.

Custom attributes refer to attributes that derive from System.Attribute that are not standard attributes in the .NET framework.

erash
+2  A: 

Attributes are used for meta-programming. meta-programming helps you achieve dynamism with your code at runtime. Say you have 10 props in your class and you want to read only some specific props for some reason, to do this you will apply some special attributes to those props and at runtime, via reflection you will ask to filter only those props with given special attributes and then perform your job on those props. This is just one example.

In our case, we have attribute driven validation framework. so if want a prop. to be not left empty before the object is saved into database, we will mark it as NotNullOrEmpty attribute and the base class will have a method Validate() which will be called before saving the object to the database. The Validate() method will filter obj. props. with Validatable attributes and perform validation and throw exception in case validation is violated.

this. __curious_geek
Great explanation and example, I just have such case right now, so thank you!
macias
A: 

When you write your code you answer the "what?" question:

  1. what to do? (methods)
  2. what to store? (fields and properties)
  3. what is what? (class hierarchies)

etc. Attributes add another dimension to this question. They answer the "how?" question. And the reply to the "how?" question may be important for IDE,

[Browsable(false)]
public string NotImportantField { get; set; } // property which will not be displayed in VS

for the compiler

[ThreadStatic]
private static RequestContext context; // field which will be different for every thread

or for another code which analyzes yours via reflection.

[XmlIgnore]
public string NotSerializableField { get; set; } // property which will not be xml-serialized

you might want to define custom attributes, if your assemblies, classes, fields, methods, etc. will be analyzed or invoked via reflection (which is often the case for example with inversion of control containers and aspect-oriented programming). Such attribute might (and often are the only way to) instruct the invoker or analyzer to behave differently depending on such attribute presence or its properties.

About your first question, well, how we know which method to call for a particular result? One of the advantages of being a .NET developer is that everything is documented pretty thoroughly. :)

A: 

Attributes are used when you want to specify certain kind of constrains to your programming statements:

Exapmple:

[StructLayout(LayoutKind::Sequential)]
value struct Point
{
public:
   int x;
   int y;
};

Above you are defining that the structure should be a sequential one.

Another example is:

 [DllImport("user32.dll",CallingConvention=CallingConvention::StdCall)]

Here you are specifying to import a dll using DLLImport by using attributes. I hope you are able to find out what is the purpose of attribute.

Now how to know which attributes to be used when and which functionality is the same as How you learnt Function, Delegate and Events ...by the course of time and using it. Also many people might have answered the same for you.

Subhen
A: 

If you want a very usable example of where attributes can be useful, and how to do the reflection code to access them, check Enum ToString. Using that code, it becomes easy to bind a ComboBox to your enum to have typesafe choices, as well as pretty human-readable descriptions:

public static void ComboItemsFromEnum<EnumType>(ComboBox combobox) where EnumType : struct
{
    combobox.FormattingEnabled = true;
    foreach (object enumVal in System.Enum.GetValues(typeof(EnumType)))
    {
        combobox.Items.Add(enumVal);
    }
    combobox.Format += delegate(object sender, ListControlConvertEventArgs e)
    {
        e.Value = GetDescription<EnumType>(e.Value);
    };
}
snemarch