| Severity | Error |
| Reported by | PostSharp.Patterns.Common |
| Message | Cannot apply the [<Attribute>] attribute to "<Member>" because its type is a string, a delegate, or a value type. |
Cause
The AggregatableAttribute aspect tracks relationships between objects. A string, a delegate, a primitive type, an enum or another value type holds a value, not an object of the graph, so it can be neither a child, nor a reference, nor a parent. PostSharp reports COM004 when a field or an automatic property of such a type has a ChildAttribute, ReferenceAttribute or ParentAttribute attribute.
A value type can take part in a relationship only when it implements IAttachable or when a type adapter registered for it allows it, for example for an ImmutableArray<T> of objects.
In the following example, the Name property of Customer, of type string, has the [Reference] attribute.
using System;
using PostSharp.Patterns.Model;
namespace Errors.COM004_Error;
[Aggregatable]
public class Customer
{
// A string cannot be a child, a reference or a parent.
[Reference]
public string Name { get; set; } = "Alice";
public decimal CreditLimit { get; set; } = 1000;
}
public static class Program
{
public static void Main()
{
Customer customer = new Customer();
Console.WriteLine( $"{customer.Name}: {customer.CreditLimit}" );
}
}
error COM004: COM004_Error.cs(11,19): Cannot apply the [ReferenceAttribute] attribute to "Errors.COM004_Error.Customer.Name" because its type is a string, a delegate, or a value type.
Resolution
Remove the attribute: fields and properties whose type cannot be a child need no relationship attribute, and the AggregatableAttribute aspect ignores them.
In the following example, the Name property has no attribute.
using System;
using PostSharp.Patterns.Model;
namespace Errors.COM004_Fixed;
[Aggregatable]
public class Customer
{
// A string needs no relationship attribute.
public string Name { get; set; } = "Alice";
public decimal CreditLimit { get; set; } = 1000;
}
public static class Program
{
public static void Main()
{
Customer customer = new Customer();
Console.WriteLine( $"{customer.Name}: {customer.CreditLimit}" );
}
}
Alice: 1000
See Also
Reference
AggregatableAttribute
ChildAttribute
ReferenceAttribute
ParentAttribute
Other Resources
Annotating an Object Model for Parent/Child Relationships (Aggregatable)