Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prior to C# 11, every field in a struct had to be explicitly assigned? Cannot reproduce

According to the book C#12 in a Nutshell:

Prior to C# 11, every field in a struct had to be explicitly assigned
in the constructor (or field initializer). This restriction has now
been relaxed.

However this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System;

Point point = new Point();
Console.WriteLine(point.X);

struct Point
{
    public int X;
    public int Y;
}

compiles and runs (returns 0) when compiled with .NET 5 (which is C#9 if I understand correctly? source: https://dotnet.microsoft.com/en-us/download/dotnet/5.0).

MRE: https://dotnetfiddle.net/K6cu5z.

>Solution :

The code you’ve written has always been fine – you’re calling the parameterless constructor, which assigns all fields to their default values.

If you change your code to:

Point point;
Console.WriteLine(point.X); // Error

… then you’ll see the error.

Note that if you fully initialize it – without ever calling new – it’s fine:

Point point;
point.X = 10;
point.Y = 20;
Console.WriteLine(point.X); // Fine

But in terms of the book’s text, if it says: "every field had to be explicitly assigned in the constructor (or field initializer)" then that doesn’t say anything about your code, because you don’t declare any constructors.

Here’s an example which actually demonstrates that rule:

struct Point
{
    public int X;
    public int Y;

    public Point(int x)
    {
        X = x;
        // Error before C# 11: Y isn't assigned
    }
}

If you build this with <LangVersion>10</LangVersion> you’ll get an error; use <LangVersion>11</LangVersion> and it builds.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading