1

I'm trying to take an advantage of AOP with custom attributes and I want to implement a custom attribute which affects return method value based on input parameters. There is a way to define an attribute for a return value:

[return: CustomAttribute]
public string Do(string param1)
{
    // do something
}

but I couldn't find a way how add a desired behavior when this attributes is applied. I want to execute some code, based on value of input parameters and in certain cases even change the output value.

Mando
  • 11,414
  • 17
  • 86
  • 167

2 Answers2

2

C# does not provide any AOP related syntax. [return: CustomAttribute] adds metadata information to return type. That's not what you expect at all. In order to leverage AOP you need to either:

  • Use an external library designed specifically to allow AOP. Here's a nice list of such libraries.
  • If you're using container then it may support AOP. For instance here's a link to StructureMap AOP related documentation.
  • You may try to implement AOP features on your own, but it's pretty hard (especially if you care about performance).
Community
  • 1
  • 1
  • I was ready to get this answer... my research already told me that .net and c# are not ready for AOP – Mando Feb 10 '17 at 20:25
  • 1
    Well, that's not entirely true. :) .NET and C# are just fine with AOP. There is no syntax designed explicitly to use aspects, but there are plenty of libraries which gives such capabilities. I've edited my answer to include [this link](http://stackoverflow.com/questions/633710/what-is-the-best-implementation-for-aop-in-net). – Damian Kamiński Feb 10 '17 at 21:12
-1

Here's a way to do something ugly, which gets your result, but it's well... ugly.

public class UglySolution
{
    private static string _changedString;

    private class CustomAttribute : Attribute
    {
        public CustomAttribute()
        {
            _changedString = "New";
        }
    }

    public class SomeClass
    {
        public SomeClass()
        {
            _changedString = "Original";
        }

        [Custom]
        public string GetValue()
        {
            typeof(SomeClass).GetMethod("GetValue").GetCustomAttributes(true).OfType<CustomAttribute>().First();
            return _changedString;
        }
    }
}
Svek
  • 12,350
  • 6
  • 38
  • 69