Open sandboxFocusImprove this doc

LA0142: Instance Constructed Advice Returns a Value

Severity Error
Reported by PostSharp
Message Method "<Method>" must have no return type because it is annotated by the advice [OnInstanceConstructedAdvice].

Cause

A method of an aspect annotated with OnInstanceConstructedAdvice runs once an instance of the target class is constructed, whichever constructor ran. PostSharp has no use for a value returned by this advice, so the method must return void. PostSharp reports LA0142 on the method, <Method>, when it returns anything else.

In the following example, the advice method of the [CountInstances] aspect returns the number of instances.

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

namespace Errors.LA0142_Error;

[PSerializable]
public class CountInstancesAttribute : InstanceLevelAspect
{
    private static int count;

    // The advice method returns the new count instead of void.
    [OnInstanceConstructedAdvice]
    public int OnInstanceConstructed()
    {
        count++;
        Console.WriteLine( $"{this.Instance!.GetType().Name} #{count} constructed" );

        return count;
    }
}

[CountInstances]
public class Order
{
}

public static class Program
{
    public static void Main()
    {
        _ = new Order();
        _ = new Order();
    }
}
error LA0142: LA0142_Error.cs(15,16): Method "Errors.LA0142_Error.CountInstancesAttribute.OnInstanceConstructed" must have no return type because it is annotated by the advice [OnInstanceConstructedAdvice].

Resolution

Change the return type of the method to void. When other code needs the value that the method computed, store it in a field or a property of the aspect instead. The method must also be public, or PostSharp reports LA0087.

In the following example, the advice method returns void.

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

namespace Errors.LA0142_Fixed;

[PSerializable]
public class CountInstancesAttribute : InstanceLevelAspect
{
    private static int count;

    // The advice method returns void.
    [OnInstanceConstructedAdvice]
    public void OnInstanceConstructed()
    {
        count++;
        Console.WriteLine( $"{this.Instance!.GetType().Name} #{count} constructed" );
    }
}

[CountInstances]
public class Order
{
}

public static class Program
{
    public static void Main()
    {
        _ = new Order();
        _ = new Order();
    }
}
Order #1 constructed
Order #2 constructed

See Also

Reference

OnInstanceConstructedAdvice
InstanceLevelAspect

Other Resources

Advice Methods
Advice Parameters