1

I've created a custom attribute which writes to the console when it's hit, however it doesn't seem to be hit. It's the microsoft tutorial (http://msdn.microsoft.com/en-us/library/sw480ze8.aspx) and is being run on 2010, .net 4. I'm guessing it must be me that's doing something wrong, but I can't see what it is. Can anyone help?

This is the attribute, whose code is never being hit

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class Author : Attribute
{
    private string _name;
    private double _version;

    public Author(string name)
    {
        Console.WriteLine(string.Format("author {0} was just created", name));

        _name = name;
        _version = 1.0;
    }
}

This is the class that uses it - it's successfully writing out the code in the constructor:

/// <summary>
/// TODO: Update summary.
/// </summary>
[Author("P. Ackerman")]
public class Ackerman
{
    public Ackerman()
    {
        Console.WriteLine("I created Ackerman.");
    }
}

And this is the console app that calls it and is successfully printing out the code in the new Ackerman() constructor:

    static void Main(string[] args)
    {
        Ackerman author1 = new Ackerman();
        Console.ReadLine();
    }

Thanks!!

rozza
  • 927
  • 2
  • 11
  • 24
  • The attribute is against the Type definition not against an instance of the Type so you won't see the attribute constructor called unless you try to inspect it – kaj Mar 16 '12 at 11:25

1 Answers1

3

Instances of attributes on class are not created then you create instance of class. Only then you specifically asks for them like this:

var attrib = author1.GetType().GetCustomAttributes(false);

This code will trigger your Console.WriteLine(string.Format("author {0} was just created", name));

Nikolay
  • 3,658
  • 1
  • 24
  • 25
  • Thanks for that - you're totally right. But what's the point of having an attribute if you have to call it separately? – rozza Mar 16 '12 at 11:22
  • 1
    Attributes are useful in many situations usually for declarative programming. You can read about some standard attributes like Serializable, DataMember, ServiceContract and so on. You can use your Author attribute for example to show all classes of specific author. You also should read about Aspect Oriented programming, because it does pretty much exactly the same that your tried to do with attributes – Nikolay Mar 16 '12 at 11:32