| Severity | Error |
| Reported by | PostSharp.Patterns.Caching |
| Message | Cannot add the [Cache] aspect to the <Method> method because it does not return a value: its return type is "void" or "Task". |
Cause
The CacheAttribute aspect stores the return value of a method in the cache, and returns the stored value instead of executing the method again when it is called with the same arguments. A method that returns void has no value to store, and neither has an asynchronous method that returns the non-generic Task. PostSharp therefore reports CAC001 when you apply the aspect to such a method.
In the following example, the [Cache] aspect is applied to PrintSalesReport, which writes the report to the console instead of returning it.
using System;
using PostSharp.Patterns.Caching;
using PostSharp.Patterns.Caching.Backends;
namespace Errors.CAC001_Error;
public class ReportService
{
public int Computations { get; private set; }
[Cache]
public void PrintSalesReport( int year ) // The method returns no value that the cache could store.
{
this.Computations++;
Console.WriteLine( $"Sales report for {year}" );
}
}
public static class Program
{
public static void Main()
{
CachingServices.DefaultService.Backend = new MemoryCachingBackend();
var service = new ReportService();
service.PrintSalesReport( 2026 );
service.PrintSalesReport( 2026 );
Console.WriteLine( $"Computations: {service.Computations}" );
}
}
error CAC001: CAC001_Error.cs(12,17): Cannot add the [Cache] aspect to the Errors.CAC001_Error.ReportService.PrintSalesReport(System.Int32) method because it does not return a value: its return type is "void" or "Task".
Resolution
- Make the method return the value that you want to cache, and let the caller use it. For an asynchronous method, return
Task<T>instead ofTask. - If the method performs an action rather than computing a value, remove the
[Cache]aspect: there is nothing to cache.
In the following example, GetSalesReport returns the report, so the second call reads it from the cache and the method is executed only once.
using System;
using PostSharp.Patterns.Caching;
using PostSharp.Patterns.Caching.Backends;
namespace Errors.CAC001_Fixed;
public class ReportService
{
public int Computations { get; private set; }
[Cache]
public string GetSalesReport( int year ) // The method returns the report, and the caller prints it.
{
this.Computations++;
return $"Sales report for {year}";
}
}
public static class Program
{
public static void Main()
{
CachingServices.DefaultService.Backend = new MemoryCachingBackend();
var service = new ReportService();
Console.WriteLine( service.GetSalesReport( 2026 ) );
Console.WriteLine( service.GetSalesReport( 2026 ) );
Console.WriteLine( $"Computations: {service.Computations}" );
}
}
Sales report for 2026
Sales report for 2026
Computations: 1
See Also
Reference
Other Resources