Aniket Inge
Aniket Inge

Reputation: 25725

Calling the constructor of an attribute automatically - C#

Is there any way to call the CallCommonCode() attribute constructor automatically when CodedMethod() is called?

using System;

[AttributeUsage(AttributeTargets.Method|AttributeTargets.Struct,
                   AllowMultiple=false,Inherited=false)]
public class CallCommonCode : Attribute
{
    public CallCommonCode() { Console.WriteLine("Common code is not called!"); }
}

public class ConcreteClass {

  [CallCommonCode]
  protected void CodedMethod(){
     Console.WriteLine("Hey, this stuff does not work :-(");
  }
  public static void Main(string[] args)
  {
     new ConcreteClass().CodedMethod();
  }
}

Upvotes: 0

Views: 1305

Answers (1)

sircodesalot
sircodesalot

Reputation: 11439

No, because the attribute exists independently of the function. You can scan for the attribute or you can execute the function, but you can't do both at the same time.

The point of an attribute is just to tag stuff with extra metadata, but it's not strictly speaking actually part of the code itself.

What you would normally do in this situation is scan for the tag on the function, and if it goes against your business logic, you would throw some sort of exception. But in general, an attribute is just a 'tag'.

class Program
{
    [Obsolete]
    public void SomeFunction()
    {

    }

    public static void Main()
    {
        // To read an attribute, you just need the type metadata, 
        // which we can get one of two ways.
        Type typedata1 = typeof(Program);       // This is determined at compile time.
        Type typedata2 = new Program().GetType(); // This is determined at runtime


        // Now we just scan for attributes (this gets attributes on the class 'Program')
        IEnumerable<Attribute> attributesOnProgram = typedata1.GetCustomAttributes();

        // To get attributes on a method we do (This gets attributes on the function 'SomeFunction')
        IEnumerable<Attribute> methodAttributes = typedata1.GetMethod("SomeFunction").GetCustomAttributes();
    }
}

Upvotes: 2

Related Questions