I have a very minimal .NET 6 program:
using System.Numerics;
var transform = new Transform2(default);
public readonly record struct Transform2(Vector2 Position, float Rotation)
{
public Transform2(Vector2 position) : this()
{
Position = position;
}
}
When I run it, I get an exception:
System.InvalidProgramException: Common Language Runtime detected an invalid program.
at Transform2..ctor(Vector2 position)
Why does this happen? Is it a bug in the C# compiler?
CodePudding user response:
Looking into this with SharpLab, you will find this = default(Transform2); in the constructor which is weird and seem to be a bug as mentioned by Matthew Watson in the comments. Any way, I don't see any reason not to change the constructor to public Transform2(Vector2 position) : this(position, default) which does not seem to cause this problem.
CodePudding user response:
Based on Sohaiub Jundi's answer, I used SharpLab to dig some more (that site is awesome!), turns out the latest Roslyn build flags this as a compiler error:
error CS8982: A constructor declared in a 'record struct' with parameter list must have a 'this' initializer that calls the primary constructor or an explicitly declared constructor.
So apparently it is a bug in the currently latest .NET 6 version, and will be fixed in an upcoming release.
A workaround for now is to explicitly call the full constructor with all arguments:
using System.Numerics;
var transform = new Transform2(default);
public readonly record struct Transform2(Vector2 Position, float Rotation)
{
public Transform2(Vector2 position) : this(position, default)
{
Position = position;
}
}
