locked
CustomAttribute Basic Question RRS feed

  • Question

  • Hi all

    I am getting frustrated why a 'hello world' doesn't work for me on a testing console application
    can someone please help me with this ?

    namespace Test 
    {
     class Program 
     { 
      static void Main(string[] args) 
      { 
        new Program().Run(); 
        Console.ReadLine();
      } 
      
      [HelloAttribute] 
      public void Run() 
      {
      } 
     } 
    
     [AttributeUsage(AttributeTargets.All,
                 Inherited = false,
                 AllowMultiple = true)] 
     public class HelloAttribute : Attribute 
     { 
      public HelloAttribute() 
      { 
       Console.WriteLine("hello world"); 
      } 
     } 
    }
    

     now, when I use the breakline on HelloAttribute Constructor , it seems the application doesnt even steps into the constructor As this is really basic and I dont find what I did do wrong, i am asking this newbie question out of you please :|

    Sunday, September 19, 2010 10:55 AM

Answers

All replies

  • The Attribute's constructor is only invoked when you actually request which attributes are present on the method you're running. So they cannot be used to run code along side a method.

    When you use reflection to get the attribute, your code will be executed:

    typeof(Program).GetMethods("Run").GetCustomAttributes()[0] or something along that line.

    What you're looking for looks a lot like aspect oriented programming, and though there are libraries that support that in .NET, it's not supported by default. Post# is an example of such a library:

    http://www.sharpcrafters.com/postsharp/documentation/getting-started

    Sunday, September 19, 2010 11:36 AM
  • Thanks Jesse

    That post# seems pretty close

    I am searching for a way to execute something on method/class start and on it's exit

    but it seems that this post# cost like 200$ for 1 user , and I'm pretty much a poor hobby developer that 200$ is just way too much for him

    do you know any other libraries that gives me the enter method and exit method expandings?

    Sunday, September 19, 2010 12:15 PM
  • What you're looking for is an Aspect Oriented Programming library for .NET.

    There are a number of free alternatives:

    I haven't tried them all, so I cannot give you any advice on which ones are better than others. Other than that the Spring variant has a very strong following in the Java community as well and is very well supported and documented.

    • Proposed as answer by Jesse HouwingMVP Sunday, September 19, 2010 1:06 PM
    • Marked as answer by strictDesign Sunday, September 19, 2010 1:42 PM
    Sunday, September 19, 2010 1:05 PM