Attributes in C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

C# provides a mechanism for defining declarative tags, called attributes, which you can place on certain entities in your source code to specify additional information. The information that attributes contain can be retrieved at runtime through reflection. You can use predefined attributes, or you can define your own custom attributes.

One very powerful predefined attribute is DllImport, which allows you to bring in existing Windows dynamic-link libraries to utilize software development kit functionality.

[DllImport("winmm.dll ")]

Another useful attribute is the conditional attribute (see Listing 5.48), which works just like #ifdef but looks a little better.

Listing 5.48: Attributes Example


[Conditional("_DEBUG")]

void
DumpDebugInfo()
{
System.Console.WriteLine(MyErrors);
}


Listing 5.49 shows what a custom attribute looks like.

Listing 5.49: Attribute.cs, Custom Attributes Example

// Example Custom Attribute

using
System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,
AllowMultiple = true)]

public
class Writer : Attribute
{
    public Writer(string name)
    {
        this.name = name; version = 1.0;
    }
    public double version;
    string name;
    public string GetName()
    {
        return name;
    }
}

[Writer("Mehmet Akif Ersoy")]

class
FirstClass
{
    /*...*/
}

class
SecondClass // no Writer attribute
{
    /*...*/
}

[Writer("Mehmet Akif Ersoy"), Writer("Necip Fazil Kisakurek", version = 1.1)]

class
Steerage
{
    /*...*/
}

class
WriterInfo
{
    public static void Main()
    {
        PrintWriterInfo(typeof(FirstClass));
        PrintWriterInfo(typeof(SecondClass));
        PrintWriterInfo(typeof(Steerage));
    }

    public static void PrintWriterInfo(Type t)
    {
        Console.WriteLine("Writer information for {0}", t);
        Attribute[] attrs = Attribute.GetCustomAttributes(t);

        foreach (Attribute attr in attrs)
        {
            if (attr is Writer)
            {
                Writer a = (Writer)attr;
                Console.WriteLine(" {0}, version {1:f}",
                a.GetName(), a.version);
                Console.ReadLine();
            }
        }
    }
}


Figure 5.11 shows the screen output generated by this code.

fig-5.11.gif

Figure 5.11: Screen Output Generated from Listing 5.49

Conclusion

Hope this article would have helped you in understanding attributes in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Similar Articles