Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I cannot set and call value using setter and getter

Learning Setter and Getter

I am making a console log app where I create a Box class and make an object and set values: width, height, and length using setter and getter. I was referencing an solution on github, but I haven’t make it work yet. I don’t know where I made mistake.

My Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System;

namespace ClassDemo2
{
    class Box
    {
        private double _width;
        private double _height;
        private double _length;

        public double Width
        {
            get { return _width; }
            set { this._width = Width; }
        }

        public double Height
        {
            get { return _height; }
            set { this._height = Height; }
        }

        public double Length
        {
            get { return _length; }
            set {this._length = Length; }
        }

        public double volume()
        {
            return Width * Height * Length;
        }

    }

    public class Program
    {
        static void Main(string[] args)
        {
            Box box = new Box();

            //Set value
            box.Width = 12;
            box.Height = 12;
            box.Length = 12;

            //Get value
            double width = box.Width;
            double height = box.Height;
            double length = box.Length;

            Console.WriteLine("Box properties");
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Height: {0}", height);
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Volume: {0}", box.volume());
        }
    }

}

Console Window

enter image description here

>Solution :

The setters in the Box class aren’t doing anything. The setters aren’t assigning a value to the private fields in the Box class.

You may as well remove the fields altogether and use auto-implemented properties.

For example:

class Box
{
    public double Width { get; set; }

    public double Height { get; set; }

    public double Length { get; set; }

    public double Volume()
    {
        return Width * Height * Length;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading