-3

It seems there is a conflict between constructor and setter for "Diameter". The error shows when I try to define a Sphere object.

using System;

namespace Challenge6
{
    class Sphere
    {
        public double Diameter
        {
            get => Diameter;
            set => Diameter = value;
        }
        public double Volume => (4.0 / 3.0) * Math.PI * Math.Pow(Diameter, 3) / 8.0;
        public double Surface => 4 * Math.PI * Math.Pow(Diameter, 2) / 4.0;
        public Sphere (double dia)
        {
           Diameter = dia;
        }
    }
}
  • Read the code, carefully. Especially your property declaration. – Ian Kemp Dec 07 '20 at 21:16
  • Use it for future debuggings. https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2019#:~:text=To%20set%20a%20breakpoint%20in,and%20select%20Breakpoint%20%3E%20Insert%20breakpoint. – Miraziz Dec 07 '20 at 21:17
  • Getter and setter of the property `Diameter` ask to access `Diameter`, so that asks to access `Diameter`, that asks to access `Diameter`, that asks to access `Diameter`, that asks to access `Diameter`... so the stack overflow exception because there is no ending. Thus you need to use an auto property, or a private or protected field acting as a "*buffer*" to store the real value, like **`_Diameter`**, to be able to do a process on the data. I hope this can help you to enjoy C# coding: [How do I improve my knowledge in C#](http://www.ordisoftware.com/files/stack-overflow/CsharpBegin.htm) –  Dec 08 '20 at 05:21
  • Thank you so much for your helps... it sounds logical. – Masoud Hosseiny Dec 08 '20 at 18:56

1 Answers1

4

If I instantiate your class and request the value of the Diameter property, it goes to the "get" method of Diameter, which returns the Diameter property - which, in order to do that, goes to the "get" method of Diameter, which returns the Diameter property, which.... do you see the problem now? You end up with infinite recursion.

Is there any particular reason you didn't just write a standard auto-implemented property?

public double Diameter { get; set; }

will do all you need.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • yes it works, and even when I delete the setter code, but some times I wanna check the value of Diameter for positive values and I don't have wrote it yet. so I need the setter code. – Masoud Hosseiny Dec 07 '20 at 21:29
  • 1
    you mean you want to check the value before agreeing to set it? In that case you'll need to use a separate backing field (see https://stackoverflow.com/a/6127320/5947043 for example). One thing's for sure though, you can't tell the property to store the value inside itself - because that's when you get the infinite loop. – ADyson Dec 07 '20 at 21:32
  • Yes... that's seems reasonable... thank you for clearing the problem. – Masoud Hosseiny Dec 08 '20 at 18:53