0

If I re-write the following code with auto-implemented properties, I understand I have to use a constructor to assign initial values to the variables.

But what happens to the override method? When I remove it, the program does not output anything...

In other words, if I use a constructor and then add auto-implemented properties, I can no longer just use rectangle to simply print out both width and height. Can I?

using System;

namespace Rectangle_Solution
{
    public class Rectangle
    {
        private int width  = 5;
        private int height = 3;

        public int Width
        {
            get
            {
                return width;
            }
            set
            {
                width = value;
            }
        }

        public int Height
        {
            get
            { 
                return height;
            }
            set
            { 
                height = value;
            }
        }

        public override string ToString()
        {
            return "width = " + Width + ", height = " + Height;
        }

        public static void Main( string[] args )
        {
            Rectangle rectangle = new Rectangle();
            Console.WriteLine( "rectangle details - {0}", rectangle );

            rectangle.width   = 10;
            rectangle.height += 1;
            Console.WriteLine( "rectangle details - {0}", rectangle );
        }
    }
}
  • 1
    You cannot provide a default-value for auto-implemented properties. – MakePeaceGreatAgain Jun 16 '15 at 10:32
  • 3
    @HimBromBeere ... *yet*. Just wait until the next .NET version :) – nvoigt Jun 16 '15 at 10:33
  • 1
    Do it in class constructor – jparaya Jun 16 '15 at 10:36
  • Thank you all. I understand better now. Another quick question: If I do it by using a constructor and then adding the auto-implemented properties, what happens to the override method then? When I remove it, the program does not output anything... –  Jun 16 '15 at 10:50
  • To state my question differently, if I do it by using a constructor and then adding the auto-implemented properties, I can no longer just use `rectangle` to print out both width and height. Can I? –  Jun 16 '15 at 10:57
  • 1
    @Jtech using auto-implemented properties will not change how your class looks when you "print" it. you need to override `ToString` regardless. – Michael Edenfield Jun 16 '15 at 12:12

0 Answers0