Open sandboxFocusImprove this doc

LAMA0283: Compile-time types can't have a primary constructor

Severity Error
Reported by Metalama.Framework
Message The compile-time type '<Type>' has a primary constructor, which is not supported in compile-time code. Remove the parameter list from the type and declare an explicit constructor instead.

Cause

C# 12 introduced primary constructors for classes and structs: a parameter list placed directly after the type name. Metalama doesn't support primary constructors in compile-time code.

Metalama reports LAMA0283 when a class or struct whose scope is compile-time or run-time-or-compile-time declares a primary constructor. This includes aspects, fabrics, and types marked with [CompileTime] or [RunTimeOrCompileTime]. Records aren't affected: their primary constructors are supported.

In the following example, the Log aspect receives its category through a primary constructor.

1using Metalama.Framework.Aspects;
2using System;
3
4namespace Doc.LAMA0283.Error;
5
6// Compile-time classes, including aspects, can't have a primary constructor.
Error LAMA0283: The compile-time type 'LogAttribute' has a primary constructor, which is not supported in compile-time code. Remove the parameter list from the type and declare an explicit constructor instead.

7public class LogAttribute( string category ) : OverrideMethodAspect
8{
9    private readonly string _category = category;
10
11    public override dynamic? OverrideMethod()
12    {
13        Console.WriteLine( $"[{this._category}] Entering {meta.Target.Method}." );
14
15        return meta.Proceed();
16    }
17}
18
1namespace Doc.LAMA0283.Error;
2
3public class Calculator
4{
5    [Log( "Math" )]
6    public int Add( int a, int b ) => a + b;
7}
8

Resolution

Remove the parameter list from the type declaration and declare an explicit constructor that initializes the fields or properties, as in the following example.

1using Metalama.Framework.Aspects;
2using System;
3
4namespace Doc.LAMA0283.Fixed;
5
6public class LogAttribute : OverrideMethodAspect
7{
8    private readonly string _category;
9
10    // The primary constructor is replaced by an explicit constructor.
11    public LogAttribute( string category )
12    {
13        this._category = category;
14    }
15
16    public override dynamic? OverrideMethod()
17    {
18        Console.WriteLine( $"[{this._category}] Entering {meta.Target.Method}." );
19
20        return meta.Proceed();
21    }
22}
23
Source Code
1namespace Doc.LAMA0283.Fixed;
2


3public class Calculator
4{
5    [Log( "Math" )]
6    public int Add( int a, int b ) => a + b;



7}
8
Transformed Code
1using System;
2
3namespace Doc.LAMA0283.Fixed;
4
5public class Calculator
6{
7    [Log("Math")]
8    public int Add(int a, int b)
9    {
10        Console.WriteLine("[Math] Entering Calculator.Add(int, int).");
11        return a + b;
12    }
13}
14

See also