Open sandboxFocusImprove this doc

Automatically ignoring property values without boilerplate

This very sample aspect overrides the target field or property so that any attempt to set it to one of the forbidden value is simply ignored.

Source Code
1internal class Author
2{


3    [IgnoreValues( "", null )]
4    public string Name { get; set; }
5
6    public Author( string name )
7    {
8        this.Name = name;
9    }
10}
Transformed Code
1internal class Author
2{
3private string _name = default!;
4
5    [IgnoreValues( "", null )]
6    public string Name { get { return _name; } set { if (value == "") { return; } if (value == null) { return; } this._name = value; } }
7
8    public Author( string name )
9    {
10        this.Name = name;
11    }
12}

Implementation

The aspect class is derived from FieldOrPropertyAspect, which itself derives from Attribute.

The aspect constructor accepts the list of forbidden values, and stores them as a field.

8private readonly object?[] _ignoredValues;
9
10public IgnoreValuesAttribute( params object?[] values )
11{
12    this._ignoredValues = values;
13}
14

The OverrideProperty property is the template overriding the original property. The getter implementation, get => meta.Proceed(), means that the getter is not modified. In the setter, we have a compile-time foreach loop that, for each forbidden value, tests if the assigned value is equal to this forbidden value and, if it is the case, returns before calling meta.Proceed(), i.e. before assigning the underlying field.

16
17public override dynamic? OverrideProperty
18{
19    get => meta.Proceed();
20    set
21    {
22        foreach ( var ignoredValue in this._ignoredValues )
23        {
24            if ( value == meta.RunTime( ignoredValue ) )
25            {
26                return;
27            }
28        }
29
30        meta.Proceed();
31    }
32}
33

This simple approach works well for most types you can use in an attribute constructor, but not for all of them:

  • For enums (except .NET Standard 2.0 enums), the constructor will receive the underlying integer value instead of a typed value. This means that our comparison will generate invalid C# because it will compare an enum to an integer.
  • For arrays, a simple == comparison is not sufficient.

Both cases could be handled by a more complex aspect. However, in this example, we will simply prevent the aspect from being applied to fields or properties of an unsupported type. We achieve this by implementing the BuildEligibility method.

34public override void BuildEligibility( IEligibilityBuilder<IFieldOrProperty> builder )
35{
36    var supportedTypes =
37        new[]
38        {
39            typeof(int),
40            typeof(uint),
41            typeof(long),
42            typeof(ulong),
43            typeof(float),
44            typeof(double),
45            typeof(decimal),
46            typeof(short),
47            typeof(sbyte),
48            typeof(byte),
49            typeof(ushort),
50            typeof(char),
51            typeof(string),
52            typeof(bool),
53            typeof(Type)
54        };
55
56    builder.Type()
57        .MustSatisfyAny(
58            supportedTypes.Select(
59                    supportedType =>
60                        new Action<IEligibilityBuilder<IType>>( t => t.MustEqual( supportedType ) ) )
61                .ToArray() );
62}

Complete source code

Here is the complete source code of the aspect.

1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Eligibility;
4
5internal class IgnoreValuesAttribute : OverrideFieldOrPropertyAspect
6{
7    // 
8    private readonly object?[] _ignoredValues;
9
10    public IgnoreValuesAttribute( params object?[] values )
11    {
12        this._ignoredValues = values;
13    }
14
15    // 
16
17    public override dynamic? OverrideProperty
18    {
19        get => meta.Proceed();
20        set
21        {
22            foreach ( var ignoredValue in this._ignoredValues )
23            {
24                if ( value == meta.RunTime( ignoredValue ) )
25                {
26                    return;
27                }
28            }
29
30            meta.Proceed();
31        }
32    }
33
34    public override void BuildEligibility( IEligibilityBuilder<IFieldOrProperty> builder )
35    {
36        var supportedTypes =
37            new[]
38            {
39                typeof(int),
40                typeof(uint),
41                typeof(long),
42                typeof(ulong),
43                typeof(float),
44                typeof(double),
45                typeof(decimal),
46                typeof(short),
47                typeof(sbyte),
48                typeof(byte),
49                typeof(ushort),
50                typeof(char),
51                typeof(string),
52                typeof(bool),
53                typeof(Type)
54            };
55
56        builder.Type()
57            .MustSatisfyAny(
58                supportedTypes.Select(
59                        supportedType =>
60                            new Action<IEligibilityBuilder<IType>>( t => t.MustEqual( supportedType ) ) )
61                    .ToArray() );
62    }
63}