Share via

debugging constructor in attribute

Esther Aronowsky 1 Reputation point
2021-05-23T11:46:39.447+00:00

I created a constructor in attribute that gets parameters. In debug it does not reach the constructor and I also see that it does not receive the value I pass. It is not clear to me what I am missing and how the constructor is being skipped at all

ForExample:

public FOO() {}

    public FOO(bool refresh)
    {
        refreshD = refresh;
    }

    public override void OnGetValue(LocationInterceptionArgs args)
    {
        if (refreshD)
        {
           ...
        }

    }

the CalledProperty:
[FOO(refresh:true)]
public ...

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


1 answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,611 Reputation points
    2021-05-24T06:44:23.753+00:00

    According to the documentation:

    It's important to note that these Attribute objects are instantiated lazily. That is, they won't be instantiated until you use GetCustomAttribute or GetCustomAttributes. They are also instantiated each time. Calling GetCustomAttributes twice in a row will return two different instances of ObsoleteAttribute.

    I tested it with the following code:

        class Program  
        {  
            [Foo(refresh:true)]  
            public string Name { get; set; }  
            static void Main(string[] args)  
            {  
                Program program = new Program() { Name = "Timon"};  
                Attribute attribute = program.GetType().GetProperty("Name").GetCustomAttribute(typeof(Foo));  
                Console.WriteLine();  
            }  
        }  
        class Foo:Attribute  
        {  
            public Foo() { }  
      
            private bool refreshD;  
            public Foo(bool refresh)  
            {  
                refreshD = refresh;  
            }  
        }  
    

    It successfully entered the Attribute.

    98976-capture.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.