The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

466790 (5) [Avatar] Offline
#1
I believe that the author intends to communicate that the following code

struct Point
{
public double X { get; private set; }
public double Y { get; private set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
}

won't compile, when he provides listing 6.11.

This code did compile and I don't understand the point that the author is trying to make by providing listing 6.11
jon.skeet (483) [Avatar] Offline
#2
It compiles when using a C# 6 compiler. It wouldn't have compiled with a C# 5 or earlier compiler.

With the C# 5 compiler you receive these errors:

Point.cs(7,1): error CS0188: The 'this' object cannot be used before all of its fields are assigned to

Point.cs(5,8): error CS0843: Backing field for automatically implemented property 'Point.X' must be fully assigned
before control is returned to the caller. Consider calling the default constructor from a constructor
initializer.
Point.cs(5,8): error CS0843: Backing field for automatically implemented property 'Point.Y' must be fully assigned
before control is returned to the caller. Consider calling the default constructor from a constructor
initializer.
466790 (5) [Avatar] Offline
#3
Yes, I am on VS 2015. So, that explains why it is compiling.

There are 2 things at play here.

1. The backing fields were initialised when the property was set.

2. No extra value can be gained by chaining the default constructor.

Is this correct?
jon.skeet (483) [Avatar] Offline
#4
Yes, the backing fields are set by the property... and chaining to the default constructor doesn't do anything extra that's beneficial in this particular case. In other cases (e.g. if you have other fields you only want to explicitly set in some constructors) then it could still be useful to do so.
466790 (5) [Avatar] Offline
#5
Thank You