Search code examples
c#attributesinstancedecorator

Will an attribute instance be created for each instance of a class in C#?


Will an attribute instance be created for each instance of a class in C#?

Here is what I mean. Let us suppose we have the following piece of code:

using System;

public class MyAttribute : Attribute
{
    public MyAttribute()
    {
        Console.WriteLine("attr got created");
    }
}

[MyAttribute()]
public class A
{
    
}

public class Program
{
    public static void Main()
    {
        new A();
        new A();
    }
}

My question is: will there be created two instances of the MyAttribute (because there are two instances of the A are created) or will there be created only a single instance of the MyAttribute which will be shared across the A instances?

Also, I suspect another possible option is that no instance of the MyAttribute will be created, because when the above code runs nothing gets output to console.

So, it is either 0, 1 or 2 instances of the MyAttribute will be created and I would like to know how many exactly. And in case the answer is not 0, then why don`t I see anything in console?


Solution

  • Attribute instances are not created until you need them. In your sample you do not get these attributes in any way, so they are not created.

    [AttributeUsage(AttributeTargets.Class)]
    public class MyAttribute : Attribute
    {
        public Guid MyGuid { get; set; }
    
        public MyAttribute()
        {
            System.Console.WriteLine("attr got created");
            MyGuid = Guid.NewGuid();
        }
    }
    
    [My]
    public class A
    {
    
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var a1 = new A();
            var a2 = new A();
    
            var attributes = new List<A> {a1, a2}.SelectMany(a => a.GetType().GetCustomAttributes<MyAttribute>());
    
            foreach (var attribute in attributes)
            {
                System.Console.WriteLine($"MyAttribute has id {attribute.MyGuid}");
            }
        }
    }
    

    With this code you can see two different guids in console output. So answer for your question is:

    New attribute instance will be created for every instance of your class but only when you need it

    EDIT: New attribute instance will be created every time you request it with GetCustomAttributes() or any similar method.