Skip to content

1.3 Using a class

  1. Make sure the Solution Explorer is visible on the left side.
  2. Go to Program.cs.
  3. Create the Main method.
  4. You will now see the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    namespace Geometry
    {
        internal class Program
        {
            static void Main(string[] args)
            {
            }
        }
    }
    

    You can now use the Circle class in your program.

  5. Type Circle myFirstCircle = new Circle();

  6. Your screen will look like this:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    using Geometry.Models;
    using System;
    
    namespace Geometry
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                Circle myFirstCircle = new Circle();
            }
        }
    }
    
    • The Circle class is automatically imported because this class is needed to execute the code.
    • Circle myFirstCircle tells the compiler that you are declaring an object of the Circle class with the name myFirstCircle. myFirstCircle is the reference variable.
    • This object does not exist yet. The object is instantiated by the new keyword.
    • Once the entire line is executed, you have a new object of the Circle class that you can access via the variable myFirstCircle.
  7. Type the following under the line you just entered: myFirstCircle followed by a period.

    You will then see the following:

    Autocompletion

    All attributes and methods in the Circle class are now available. You can modify and read the attributes and call the methods.

  8. Make sure your Main method looks like this:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    static void Main(string[] args)
    {
        Circle myFirstCircle = new Circle();
        myFirstCircle.Radius = 3;
        myFirstCircle.CenterX = 3;
        myFirstCircle.CenterY = -2;
        myFirstCircle.Color = "green";
    
        Console.WriteLine(myFirstCircle.CalculatePerimeter());
        Console.WriteLine(myFirstCircle.CalculateArea());
    }
    
  9. Run your program. Your output will look like this:

    1
    2
    18.84955592153876
    28.274333882308138
    
  10. Try some other values and view the output.