Suppose I have these classes :

class Square1 //////////
        {
            private int side = 0; //private field

            public Square1(int side) //constructor
            {
                this.side = side;
            }

            public int GetArea() //public method
            {
                return side * side;
            }
        }

        class Square2 //////////
        {
            private int side = 0; //private field

            public Square2(int side) //constructor
            {
                this.side = side;
            }

            public int Area //public property
            {
                get { return side * side; }
            }
        }

I had other methods or properties here to set the value of side, but left them out to keep it simple.
The only thing I want to expose is a calculated value of area.
What is the best option here? I think data encapsulation is taking care of in both cases, or am I wrong?
Suppose I want to derive from a Square class, call it a SuperSquare class, what is the best option? (A square drawn on a flat wall has another area then a square with the same sides drawn on a football. So I should override the area calculation in some way.)

I think a property is better because the method has extra syntax that is not needed. But they both do the same thing and are close enough that you should pick the one you like better.

Suppose I want to derive from a Square class, call it a SuperSquare class, what is the best option?

Properties can be virtual. Adding inheritance and polymorphism to the question does not change the answer. :)

Thanks for the quick answer and the clarification! Did not know you could override properties!(This is true is it?)
Comes probably from all those quadrilateral, animal and other examples I see all around me. :yawn:

Did not know you could override properties!(This is true is it?)

It is true. Properties can also be part of an interface.

Thanks for broadening my knowlegde. :)

Another 'rule of thumb' about properties versus methods is that Properties should not throw exceptions for the most part. A calculated value for a property is common (see Control.Right) but if you have to do something that may be unsafe and raise an error then a method may be better

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.