-
Notifications
You must be signed in to change notification settings - Fork 4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difference in struct initialization causing values to be copied between 2 variables #58771
Comments
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label. |
Minimal repro: using System;
class Prog
{
static int FailsWithSingleInit()
{
Foo foo = new Foo { B = 5, A = 10u };
foo = new Foo { A = 10u };
return foo.B; // expected: 0, actual: 5
}
static void Main() => Console.WriteLine(FailsWithSingleInit()); // prints 5
}
internal struct Foo
{
public uint A { get; init; }
public int B { get; init; }
public string C { get; init; } = "x";
} My impression that this a bug in Roslyn/C# (this code doesn't compile on sharplab-main, it says
^ it calls |
Is |
@mikesena, thanks for reporting this issue and for providing the detailed repro. This is #57870 and has been fixed in 17.1. With 17.1, the compiler reports errors on the struct declaration that all fields must be assigned:
|
Description
The code provided in the reproduction steps fails with the following exception, and I'm not able to explain why. I believe it may be a bug with the framework, but it may be a convention I'm not aware of.
My expectation would be that in all cases provided, the result is the same - a 'new' struct is created / allocated.
Reproduction Steps
The following code will fail on the final assertation in
FailsWithSingleInit
.I have made a slightly modified version on .NET fiddle, throwing an exception instead.
https://dotnetfiddle.net/LQh6dG
Expected behavior
All provided test examples pass, with no assertation issues.
Actual behavior
The provided code fails with the following:
Regression?
I'm not sure.
Known Workarounds
The workaround for this case, is to provide a public constructor myself, where all required to be initialised.
Configuration
.NET 6.0
Windows 10, 21H2, 19044.1415
x64
I don't believe it is specific to this configuration, but I haven't tested it on any other platforms.
Other information
Reviewing the IL code, it seems to generate a different path for the failing static method.
I believe it's something funky in there.
The text was updated successfully, but these errors were encountered: