question

EstherAronowsky-1985 avatar image
0 Votes"
EstherAronowsky-1985 asked TimonYang-MSFT commented

debugging constructor in attribute

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



dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@EstherAronowsky-1985
May I know if you have got any chance to check my answer? If my answer does not meet your expectations or have any other questions, please feel free to ask.

0 Votes 0 ·

1 Answer

TimonYang-MSFT avatar image
0 Votes"
TimonYang-MSFT answered TimonYang-MSFT edited

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.


3.png (10.2 KiB)
capture.png (8.7 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.