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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With