Inheritance - get/set in c#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jasmine82
    New Member
    • Jul 2008
    • 1

    Inheritance - get/set in c#

    Hi all
    I am trying to learn c#, at the moment i am stuck on an inheritance and set get example
    here is my code
    Main program
    [code=c#]
    static void Main()
    {
    squar sq = new squar();
    sq.squareArea() ;
    Console.WriteLi ne("The area of a square is " + Area);
    Console.Read();
    }
    [/code]
    and here is my parent and child class
    [code=c#]
    using System;

    namespace simpleInheritan ce
    {
    public class shapes
    {
    private int h;
    public int height
    {
    get{ return h;}
    set{h=10;}//<--here
    }
    }
    public int getHeight()
    {
    int theHeight = height;
    return theHeight;
    }
    }//end class shapes

    public class squar : shapes
    {
    public void squareArea()
    {
    int side = getHeight();
    int area = side * side;
    Console.WriteLi ne("area is " + area);
    }
    }
    }
    [/code]

    my question is why doesnt my set method in the shapes class (parent) get executed... only the get method is being executed...

    thanks in adavance
    Last edited by Plater; Jul 24 '08, 08:25 PM. Reason: code tags, cleanup. I think you have an extra } in there
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You're on the wrong forum, this should be in the .NET forum.

    As an fyi, you never actually call your set method that I see, unless that's C#'s idea of a constructor.

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      Originally posted by Laharl
      As an fyi, you never actually call your set method that I see, unless that's C#'s idea of a constructor.
      No, you are right, nowhere in that code is any attempt at using the set method done.

      Comment

      • Curtis Rutland
        Recognized Expert Specialist
        • Apr 2008
        • 3264

        #4
        I can give you a bit of advice here. First of all, getHeight() is doubly redundant. You make a copy of your variable to return, which is inefficient and unnecessary, but even the method itself is unnecessary. The public property height has a get method, so you can just reference height. You don't need a method to return the value, because you made the property public.

        You don't have any constructor at all. You should make a constructor that accepts a int or double, so when you create a shape, you can pass a value to it for the height. Then, make a constructor for squar that takes the same type (int or double), and make sure that it calls the base constructor.

        I understand that may be a bit much for someone just learning, but constructors are fundamental concepts that you must grasp.

        Comment

        Working...