Skip to main content

C# - Creating and Reading Global Attributes [Beginner]


Global attributes aren't something that many C# developers use often, however almost every application contains them, whether you're aware of them or not. Global attributes are a great way to store meta information for a specific assembly or module.

Global attributes are split into two categories: assembly and module. A module is a single code file and an assembly is a single DLL or executable. An assembly can contain several modules and a module can contain several classes.

When you create a new project in Visual Studio, usually it creates a file for you called AssemblyInfo.cs. This file uses global attributes to store important information about the assembly like version and copyright information. Below is an excerpt from an example AssemblyInfo.cs file.
// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GlobalAttributes")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GlobalAttributes")]
[assembly: AssemblyCopyright("Copyright ©  2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
 
In order to create our own custom attributes like these, the first thing we're going to need to do is create a class that extends Attribute to store the information.
using System;

namespace GlobalAttributes
{
  public class MyCustomAttribute : Attribute
  {
    public string MyValue { get; set; }
  }
}
 
Here I created a very basic custom attribute. It has one property, MyValue, which holds a string. Now let's see how to use the attribute in our own code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GlobalAttributes;

[assembly: MyCustomAttribute(MyValue="My assembly attribute value.")]
[module: MyCustomAttribute(MyValue = "My module attribute value.")]

namespace GlobalAttributes
{
  class Program
  {
    static void Main(string[] args)
    {

    }
  }
}
 
I started with a default console application and added the global attribute below the using statements and above the namespace declaration. Global attributes are created exactly like the more common method and class level attributes, except the scope is defined as either assembly or module.

Now that we've got some information stored in our custom global attributes, let's now look at how to read it at run-time.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GlobalAttributes;
using System.Reflection;

[assembly: MyCustomAttribute(MyValue="My assembly attribute value.")]
[module: MyCustomAttribute(MyValue = "My module attribute value.")]

namespace GlobalAttributes
{
  class Program
  {
    static void Main(string[] args)
    {
      //Get all the attributes with the type MyCustomAttribute
      object[] attributes = 
        Assembly.GetExecutingAssembly().GetCustomAttributes(
        typeof(MyCustomAttribute), false);

      //Get the first (and only) entry and print the value
      MyCustomAttribute attr = attributes[0] as MyCustomAttribute;
      Console.WriteLine(attr.MyValue);

      Console.WriteLine("Press enter to exit.");
      Console.ReadLine();
    }
  }
}
 
The first thing we need to do is actually get an Assembly object. There's lots of ways to do this, but the easiest is to simply get the currently executing one. We then call GetCustomAttributes and pass it the type of the attribute we're interested in. The boolean parameter is actually ignored by .NET when called on Assembly objects, so set it to whatever you want. I know that there's only one of these attributes applied to the assembly so I just grab the first one out and cast it to the correct type. Last, just print the value. Here's the console output of this code:
My assembly attribute value.
Press enter to exit.
Next up is module attributes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GlobalAttributes;
using System.Reflection;

[assembly: MyCustomAttribute(MyValue="My assembly attribute value.")]
[module: MyCustomAttribute(MyValue = "My module attribute value.")]

namespace GlobalAttributes
{
  class Program
  {
    static void Main(string[] args)
    {
      //Get all the attributes with the type MyCustomAttribute
      object[] attributes = 
        Assembly.GetExecutingAssembly().GetCustomAttributes(
        typeof(MyCustomAttribute), false);

      //Get the first (and only) entry and print the value
      MyCustomAttribute attr = attributes[0] as MyCustomAttribute;
      Console.WriteLine(attr.MyValue);

      //Get the attributes for the module containing the Program class
      attributes = typeof(Program).Module.GetCustomAttributes(
        typeof(MyCustomAttribute), false);

      //Get the first (and only) entry and print the value
      attr = attributes[0] as MyCustomAttribute;
      Console.WriteLine(attr.MyValue);

      Console.WriteLine("Press enter to exit.");
      Console.ReadLine();
    }
  }
}
 
Each object will belong to one Module. I get a reference to the module containing the class Program by using the Module property on the Type class. The rest of the code is exactly like assembly attributes and again, the boolean parameter to GetCustomAttributes is ignored by .NET. Here's the output of this code:
My assembly attribute value.
My module attribute value.
Press enter to exit.
 
That's it. This tutorial demonstrated how to create and read global attributes in C#. If you've got any questions, feel free to leave them below.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as