Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The code below is the example from the book "Illustrated C#2012." Can someone help me and make me understand, what should I do to implement triangle or rectangle or circle portion of the class and find out the area?

C#
{
       class Shape
{
  // Keyword Initialized
   // ↓↓
  readonly double PI = 3.1416;
  readonly int NumberOfSides;
  // ↑↑

  // Keyword Not initialized
  public Shape(double side1, double side2) // Constructor
  {
     // Shape is a rectangle
    NumberOfSides = 4;
    //
    // ... Set in constructor
  }
    public Shape(double side1, double side2, double side3) // Constructor
  {
     // Shape is a triangle
     NumberOfSides = 3;
    //
    // ... Set in constructor
   }
   }


So far I was only able to do:
{public static void Main()
{
var s = new Shape(1.0,1.2);
Console.WriteLine(s.NumberOfsides);
}
Posted
Updated 31-Mar-14 17:14pm
v2
Comments
PIEBALDconsult 31-Mar-14 23:18pm    
That's not even a good example; find a better one.
RalvarezHose 31-Mar-14 23:25pm    
That's the one exactly from the book. If you have any good books in mind please let me know.
PIEBALDconsult 31-Mar-14 23:51pm    
There's got to be a better book. Making PI a member field is ridiculous.
Even MSDN is probably better: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

1 solution

There are a number of ways to do this,
a better way would be to make this Shape an abstract class with abstract method like area and leave it to the specific shape to implement the actual area formula.
But to stick to your simple example, try this:
C#
using System;

public class Program
{
    class Shape
    {
        readonly double PI = 3.1416;
        readonly int NumberOfSides;

        // add a double member
        private double area;

        public Shape(double side1, double side2) // Constructor
        {
            // Shape is a rectangle
            NumberOfSides = 4;

            // calculate the area
            area = side1 * side2;
        }

        // add an accessor method
        public double GetArea()
        {
            return area;
        }
    }

    public static void Main()
    {
        // instantiate a rectangle object
        Shape rectangle = new Shape(10, 20);

        // get the area from the GetArea() method
        Console.WriteLine(rectangle.GetArea());
    }
}
 
Share this answer
 
v2
Comments
RalvarezHose 1-Apr-14 0:01am    
Thank you Peter. That makes a whole lot of sense than reading the same example over and over again in the book.
Peter Leow 1-Apr-14 0:10am    
You are welcome. Besides books, you may want to explore some online tutorials like http://www.tutorialspoint.com/csharp/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900