Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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:

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.

like image 333
FluidMechanics Potential Flows Avatar asked Aug 31 '25 23:08

FluidMechanics Potential Flows


1 Answers

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.

like image 87
Jon Skeet Avatar answered Sep 03 '25 12:09

Jon Skeet