| Severity | Error |
| Reported by | Metalama.Framework |
| Message | The aspect '<Aspect>' cannot introduce the union '<Union>' because a union declaration must declare at least one case. Call 'AddCase' at least once in the callback that builds the union. |
Cause
A C# union is declared by the list of its cases, such as union Result(int, string);. The language requires at least one case. When an aspect introduces a union with the IntroduceUnion method, it declares the cases by calling AddCase in the callback that builds the union.
Metalama reports LAMA0554 when this callback returns without having called AddCase. Without this check, the C# compiler would report an error on generated code, which is hard to trace back to the aspect.
In the following example, the aspect introduces the Result union without any case.
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3
4namespace Doc.LAMA0554.Error;
5
6public class IntroduceResultAttribute : TypeAspect
7{
8 public override void BuildAspect( IAspectBuilder<INamedType> builder )
9 {
10 // Error: the union declares no case.
11 builder.IntroduceUnion( "Result", u => u.Accessibility = Accessibility.Public );
12 }
13}
14
1namespace Doc.LAMA0554.Error;
2
3[IntroduceResult]
Error LAMA0554: The aspect 'IntroduceResult' cannot introduce the union 'Result' because a union declaration must declare at least one case. Call 'AddCase' at least once in the callback that builds the union.
4public class OrderService { }
5
Resolution
Call AddCase in the callback for each type that the union can hold. In the following example, the Result union has two cases, int and string.
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3
4namespace Doc.LAMA0554.Fixed;
5
6public class IntroduceResultAttribute : TypeAspect
7{
8 public override void BuildAspect( IAspectBuilder<INamedType> builder )
9 {
10 builder.IntroduceUnion(
11 "Result",
12 u =>
13 {
14 u.Accessibility = Accessibility.Public;
15
16 // The union declares its cases.
17 u.AddCase( typeof(int) );
18 u.AddCase( typeof(string) );
19 } );
20 }
21}
22
Source Code
1namespace Doc.LAMA0554.Fixed;
2
3[IntroduceResult]
4public class OrderService { }
5
Transformed Code
1namespace Doc.LAMA0554.Fixed;
2
3[IntroduceResult]
4public class OrderService
5{
6 public union Result(int, string);
7}
8