views:

194

answers:

1

The attribute which targets method is not working. The code is below. What could be the problem?

using System;
namespace AttributeProgram
{

    class Program:ContextBoundObject
    {
        [TestAttribute("Hello")]
        public void Print()
        {
            Console.WriteLine("How are you?");
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.Print();
        }
    }

    [AttributeUsage(AttributeTargets.Method)]
    class TestAttribute : System.Runtime.Remoting.Contexts.ContextAttribute
    {
        public TestAttribute(string Name) : base("Test")
        {
            Console.WriteLine(Name);
        }
    }
}
+3  A: 

Because you're inheriting from ContextAttribute which can be applied only to classes, as per documentation:

[SerializableAttribute]
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets.Class)]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public class ContextAttribute : Attribute, 
    IContextAttribute, IContextProperty
Paulo Santos