dotnet / csharpstandard

Working space for ECMA-TC49-TG2, the C# standard committee.
Creative Commons Attribution 4.0 International
723 stars 86 forks source link

Inaccurate description for `Object initializers` rule #303

Open ltcmelo opened 5 years ago

ltcmelo commented 5 years ago

In the description of how object initializers work, the language spec states that this initialization

Point a = new Point { X = 0, Y = 1 };

is equivalent to the following statements:

Point __a = new Point();
__a.X = 0;
__a.Y = 1; 
Point a = __a;

Yes, that is correct. However, in my opinion the wording used is inaccurate. The specification could better distinguish the declarator type from the initialized type, even if such differentiation is done in the wording only (if it is there, I was not able to find it). Consider

SomeInterface a = new Point { X = 0, Y = 1 };

where Point implements SomeInterface. Naively passing through the text "A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment" can be misleading, and the translation above wouldn't apply when X and Y are defined in Point. In fact, I just caught an error in my code rewriter for the case in question.

Again, the specification does not seem to be wrong in the way it is right now, but I would suggest making it a bit more precise.

YairHalberstadt commented 5 years ago

You can create a pull request with your suggested changes.

Once done I would tag BillWagner who's in charge of documentation.

ltcmelo commented 5 years ago

@YairHalberstadt , here you go: https://github.com/dotnet/csharplang/pull/2535

yaakov-h commented 5 years ago

Another interesting case where the same part of the spec is misleading:

public interface IPoint
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class Point : IPoint {
    int IPoint.X { get; set; }
    int IPoint.Y { get; set; }
}

public static class PointFactory
{
    public static IPoint MakePoint(int x, int y)
    {
        IPoint point = new Point { X = x, Y = y };
        return point;
    }
}

error CS0117: 'Point' does not contain a definition for 'X' error CS0117: 'Point' does not contain a definition for 'Y'

ltcmelo commented 5 years ago

@YairHalberstadt I created this PR a while ago, but it's still sitting there without any feedback. :(

YairHalberstadt commented 5 years ago

@BillWagner

I believe that PRs in documentation should go through you. Is that correct?

BillWagner commented 3 years ago

Moving to dotnet/csharpstandard

Note that there is an associated pull request that describes a potential fix in the csharplang repo.

@ltclemo I apologize for the delay, and the other poor experiences around the fix. We've moved the standard into this repo for the ECMA committee to continue working on updated versions (and provide fixes). Would you like to recreate your original PR here for the committee to review and include?