1

While creating a custom attribute of "AttributeTargets.Parameter" constructor is not called. I want to use the parameter value of Fn function under Test Class. I used .net core and .net standard.

class Program
{
    public static void Main()
    {
        var test = new Test();
        test.Fn("Hello");
        Console.WriteLine("end");
        Console.Read();
    }
}


public class Test
{
    public void Fn([Parameter] string parm)
    {
        Console.WriteLine(parm);
    }
}

[AttributeUsage(AttributeTargets.Parameter)]
public class ParameterAttribute : Attribute
{
    public ParameterAttribute()
    {
        Console.WriteLine("In Parameter Attribute");
    }
}

1 Answers1

4

As far as I remember, Attribute constructors are only executed when you start inspecting the type and not when an instance of that type is created or a method executed (in your case).

You can take a look at this answer for a detailed example of the order of execution when using custom Attributes.

Hope it helps!

Itay Podhajcer
  • 2,616
  • 2
  • 9
  • 14
  • 1
    Thanks, Itay, When I used my custom Attribute as a class attribute it's working fine but when I set Usage target To Parameter it stops working. I am trying to get the parameter value of the attribute. – Munendra Kumar Dec 19 '18 at 09:19
  • Take a look at [ParameterInfo.Attributes Property](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.parameterinfo.attributes?view=netframework-4.7.2#examples) on how to extract method parameters' attributes (there's an example in that link that shows exactly how it is done). – Itay Podhajcer Dec 19 '18 at 09:34