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

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV...