Search code examples
c#postsharp

In PostSharp is it possible to modify the value of a single argument to a method?


My current method can restrict operations to operate on strings, but I need finer grain control. I want to do things like, set elements to title case which would only be applicable to some params, but for this I would need to be able to operate on a per parameter level. This method provides no way of checking meta data for a single parameter, such as a custom attribute?

(I am aware there a better ways to enforce consistent format of parameters, but this demonstrates the question I am trying to answer).

/// <summary>
    /// Checks all string parameters on a method and trims the input if 
    /// a non null string is identified.
    /// </summary>
    [Serializable]
    public class TrimAllStringInputsAspect : MethodInterceptionAspect
    {
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            for (int i = 0; i < args.Arguments.Count; i++)
            {
                var argVal = args.Arguments.GetArgument(i);

                if (argVal != null)
                {
                    if (argVal is String)
                    {
                        args.Arguments.SetArgument(i, argVal.ToString().Trim());
                    }
                }
            }

            args.Proceed();
        }
    }

Solution

  • MethodInterceptionAspect is the only way to change input parameters. If you need to access metadata, you can get a MethodBase from args.Method, or better, you can implement the proper metadata logic in CompileTimeInitialize and store the result in a field, which will be serialized with the aspect at build time and deserialized at runtime.