Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

Interrogating Your Metadata

The really interesting part of metadata is being able to test against attributes at runtime. Let's assume we have the following attribute (see ObjectLibrary for the full source files):

public enum Priority
{
 Primary,
 Secondary,
 Tertiary
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface |
[ccc] AttributeTargets.Struct)]
public class OrderingPriorityAttribute : Attribute
{
 public OrderingPriorityAttribute(Priority priority)
 {
  _priority = priority;
 }

 Priority _priority;

 public Priority Priority
 {
  get { return _priority; }
  set { _priority = value; }
 }
}

For our example, we will create a simple base class:

public class BaseClass
{
}

Then we can annotate our different subclasses with the attribute using different priorities (see ObjectViewer for the full source files):

[OrderingPriority(Priority.Primary)]
public class FirstClass : BaseClass
{
}

[OrderingPriority(Priority.Secondary)]
public class SecondClass : BaseClass
{
}

[OrderingPriority(Priority.Tertiary)]
public class JustAnotherClass : BaseClass
{
}

[OrderingPriority(Priority.Tertiary)]
public class YetAnotherClass : BaseClass
{
}

Now we can create a collection of classes of the derived classes:

// Create the Instances of the BaseClass
BaseClass[] bases = new BaseClass[10];
bases[0] = new FirstClass();
bases[1] = new SecondClass();
bases[2] = new JustAnotherClass();
bases[3] = new YetAnotherClass();
bases[4] = new FirstClass();
bases[5] = new SecondClass();
bases[6] = new JustAnotherClass();
bases[7] = new YetAnotherClass();
bases[8] = new FirstClass();
bases[9] = new SecondClass();

With these objects, we can test for the attribute and keep a count of the different priority types:

// Initialize Counters
int first = 0;
int second = 0;
int tertiary = 0;

// Go through each of the items in the array
foreach (BaseClass item in bases)
{
 // Retrieve the appropriate attribute
 Attribute attr = Attribute.GetCustomAttribute(item.GetType(), 
  typeof(OrderingPriorityAttribute));

 // If the attribute is found
 if (attr != null)
 {
  OrderingPriorityAttribute order = (OrderingPriorityAttribute) attr;

  // Test the Priority of the attribute and 
  // update the counters
  if (order.Priority == Priority.Primary) first++;
  if (order.Priority == Priority.Secondary) second++;
  if (order.Priority == Priority.Tertiary) tertiary++;
 }
}

// Show the counter results
primaryLabel.Text = string.Format("Primary: {0}", first);
secondaryLabel.Text = string.Format("Secondary: {0}", second);
tertiaryLabel.Text = string.Format("Tertiary: {0}", tertiary);
  • + Share This
  • 🔖 Save To Your Account