Open sandboxFocusImprove this doc

LA0144: Advice Method Does Not Return Void

Severity Error
Reported by PostSharp
Message Advice "<Advice>" is not valid on method "<Method>": method return type must be void.

Cause

PostSharp calls an advice method from the code that it weaves into the target, and ignores what the method returns. To change the return value of the target, an advice sets the ReturnValue property of its argument instead. For this reason, the following advices require their method to return void:

PostSharp reports LA0144 on the advice method when it returns another type. <Advice> is the type of the advice custom attribute. OnMethodInvokeAsyncAdvice is the exception: its method must return a Task, and PostSharp reports LA0165 otherwise.

In the following example, the entry advice of the [Log] aspect returns a bool.

using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;

namespace Errors.LA0144_Error;

[PSerializable]
public class LogAttribute : MethodLevelAspect
{
    // An OnMethodEntryAdvice method must return void.
    [OnMethodEntryAdvice]
    public bool OnEntry( MethodExecutionArgs args )
    {
        Console.WriteLine( $"Entering {args.Method.Name}." );

        return true;
    }
}

public class OrderService
{
    [Log]
    public void PlaceOrder( string product ) => Console.WriteLine( $"Order placed: {product}" );
}

public static class Program
{
    public static void Main()
    {
        new OrderService().PlaceOrder( "Book" );
    }
}
error LA0144: LA0144_Error.cs(13,17): Advice "PostSharp.Aspects.Advices.OnMethodEntryAdvice" is not valid on method "Errors.LA0144_Error.LogAttribute.OnEntry(PostSharp.Aspects.MethodExecutionArgs)": method return type must be void.

Resolution

Make the advice method return void. To pass a value back to the target code, set the properties of the advice argument, such as ReturnValue or FlowBehavior of MethodExecutionArgs.

In the following example, the entry advice returns void.

using System;
using PostSharp.Aspects;
using PostSharp.Aspects.Advices;
using PostSharp.Serialization;

namespace Errors.LA0144_Fixed;

[PSerializable]
public class LogAttribute : MethodLevelAspect
{
    // The advice method returns void.
    [OnMethodEntryAdvice]
    public void OnEntry( MethodExecutionArgs args )
    {
        Console.WriteLine( $"Entering {args.Method.Name}." );
    }
}

public class OrderService
{
    [Log]
    public void PlaceOrder( string product ) => Console.WriteLine( $"Order placed: {product}" );
}

public static class Program
{
    public static void Main()
    {
        new OrderService().PlaceOrder( "Book" );
    }
}
Entering PlaceOrder.
Order placed: Book

See Also

Reference

OnMethodEntryAdvice
OnMethodInvokeAdvice
OnLocationGetValueAdvice
OnEventAddHandlerAdvice

Other Resources

Advice Methods