Attributes

Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection. For more information, see Reflection (C#).

Attributes have the following properties:

  • Attributes add metadata to your program. Metadata is information about the types defined in a program. All .NET assemblies contain a specified set of metadata that describes the types and type members defined in the assembly. You can add custom attributes to specify any additional information that is required. For more information, see, Creating Custom Attributes (C#).

  • You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and properties.

  • Attributes can accept arguments in the same way as methods and properties.

  • Your program can examine its own metadata or the metadata in other programs by using reflection. For more information, see Accessing Attributes by Using Reflection (C#).

using System;
using System.Linq;
using System.Reflection;

namespace Attributes
{
    class Program
    {
        static void Main(string[] args)
        {
            // A little bit about reflexion
            var types = from t in Assembly.GetExecutingAssembly().GetTypes()
                        where t.GetCustomAttributes<SampleAttribute>().Count() > 0
                        select t;

            foreach (var type in types)
            {
                Console.WriteLine(type.Name);
                foreach (var prop in type.GetProperties())
                {
                    Console.WriteLine(prop.Name);
                }
            }

            Console.ReadLine();
        }

        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Interface)]
        public class SampleAttribute : Attribute
        {
            public int MyProperty { get; set; }
            public bool Validation { get; set; }
        }

        [AttributeUsage(AttributeTargets.Class)]
        public class OtherAttribute: Attribute
        {
            public int MyProperty { get; set; }
        }

        [Sample]
        public class MyClass
        {
            [Sample]
            public int MyProperty { get; set; }
        }

        [Other(MyProperty = 2)]
        public class MyOtherClass
        {

        }


    }
}

Last updated