Attribute Class Non-Calling Constructor

I created an attribute, call MyAttribute, which performs some security, and for some reason the constructor is not fired, for some reason?

public class Driver
{
    // Entry point of the program
    public static void Main(string[] Args)
    {
        Console.WriteLine(SayHello1("Hello to Me 1"));
        Console.WriteLine(SayHello2("Hello to Me 2"));

        Console.ReadLine();
    }

    [MyAttribute("hello")]
    public static string SayHello1(string str)
    {
        return str;
    }

    [MyAttribute("Wrong Key, should fail")]
    public static string SayHello2(string str)
    {
        return str;
    }


}

[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{

    public MyAttribute(string VRegKey)
    {
        if (VRegKey == "hello")
        {
            Console.WriteLine("Aha! You're Registered");
        }
        else
        {
            throw new Exception("Oho! You're not Registered");
        };
    }
}
+5
source share
2 answers

This actually fails, but only if you are trying to get attribute properties. Here is an example that fails:

using System;

public class Driver
{
// Entry point of the program
    public static void Main(string[] Args)
    {
        Console.WriteLine(SayHello1("Hello to Me 1"));
        Console.WriteLine(SayHello2("Hello to Me 2"));

        Func<string, string> action1 = SayHello1;
        Func<string, string> action2 = SayHello2;

        MyAttribute myAttribute1 = (MyAttribute)Attribute.GetCustomAttribute(action1.Method, typeof(MyAttribute));
        MyAttribute myAttribute2 = (MyAttribute)Attribute.GetCustomAttribute(action2.Method, typeof(MyAttribute));

        Console.ReadLine();
    }

    [MyAttribute("hello")]
    public static string SayHello1(string str)
    {
        return str;
    }

    [MyAttribute("Wrong Key, should fail")]
    public static string SayHello2(string str)
    {
        return str;
    }


}

[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{

    public string MyProperty
    {
        get; set;
    }

    public string MyProperty2
    {
        get;
        set;
    }

    public MyAttribute(string VRegKey)
    {
        MyProperty = VRegKey;
        if (VRegKey == "hello")
        {
            Console.WriteLine("Aha! You're Registered");
        }
        else
        {
            throw new Exception("Oho! You're not Registered");
        };

        MyProperty2 = VRegKey;
    }
}
+1
source

Attributes are used at compile time, and constructors are used only to populate properties. Attributes are metadata and can only be checked at runtime.

In fact, Attributes should not contain any behavior whatsoever.

+8
source

All Articles