0

As far as I know when I use automatically implemented properties with struct I should explicitly chain the parameterless constructor (ie the parameterless constructor has to be called before auto implemented properties can be assigned). Now I have the following code that works correctly without chaining : this()

    public struct Foo
    {
        public int Value { get; private set; }

        public Foo(int value) //: this()
        {
            Value = value;
        }
    }

    static void Main(string[] args)
    {
        Foo f = new Foo(33);
        Console.WriteLine(f.Value);
    }

I found similar post here where the user was getting a compiler error, and it was suggested to use : this() in order to fix the problem. Why my code works without : this()? Should we use or not use : this()?

Thanks

ES2018
  • 438
  • 3
  • 15
  • Do you have an error when using `: this()` ? Could you check which C# version your VS project (or other) is targeting ? – Arthur Attout Jan 04 '19 at 17:05
  • @ArthurAttout with or without `: this()` I get the same result. I am using VS2017, .NET Framework 4.6.1 – ES2018 Jan 04 '19 at 17:09
  • 2
    Note that the question&answer you linked to are quite old. The problem this question&answer discussed is not an issue anymore since C# 6... (see the duplicate question i linked to) –  Jan 04 '19 at 17:09
  • You only need to call `this()` if you want to read value from fields or properties before setting them anything. – M.kazem Akhgary Jan 04 '19 at 17:10
  • Thanks, I read the other posts and I realized that from C# 6, it is not an issue. Thanks again – ES2018 Jan 04 '19 at 17:22

0 Answers0