Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# creating attribute that indicate running code after property call

I would like to create an Attribute to put on properties.

The properties that will contains this attribute will execute another method after setting a new value.

For example:

    [MethodExecute(Log)]
    [MethodExecute(Save)]
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

Here I would like to activate two methods, one will log the change and the other will save it.

Thanks, Ronny

like image 324
Ronny Avatar asked Sep 16 '09 06:09

Ronny


1 Answers

I believe you could do this in PostSharp. You'll need to specify the method name as a string unfortunately - there's no operator in C# to resolve a method name into MethodInfo, although it's been proposed a few times.

You may need to move the attribute if you need the code to execute only after the setter (rather than the getter):

public string Name
{ 
    get; 
    [MethodExecute("Log")] [MethodExecute("Save")] set;
}

(This uses an automatically implemented property for simplicity.)

like image 152
Jon Skeet Avatar answered Oct 15 '22 04:10

Jon Skeet