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.

2 Answers 2

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).
Sign up to request clarification or add additional context in comments.

2 Comments

I was ready to get this answer... my research already told me that .net and c# are not ready for AOP
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.
-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;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.