Book Image

Learning Object-Oriented Programming

By : Gaston C. Hillar
Book Image

Learning Object-Oriented Programming

By: Gaston C. Hillar

Overview of this book

Table of Contents (16 chapters)
Learning Object-Oriented Programming
About the Author
About the Reviewers

Creating instances of classes in C#

We already created instances of the simple Circle class. We just needed to use the new keyword followed by the class name, specify the required arguments enclosed in parentheses, and assign the result to a variable.

The following lines declare a public CalculateArea method within the body of the Circle class:

public double CalculateArea()
  return Math.PI * Math.Pow(this.radius, 2);

The method doesn't require arguments to be called. It returns the result of the multiplication of π by the square of the radius field value (this.radius). The following lines show a new version of the Main method. These lines create two instances of the Circle class: circle1 and circle2. The lines then display the results of calling the CalculateArea method for the two objects. The new lines are highlighted, as follows:

class Chapter01
  public static void Main(string[] args)
    var circle1 = new Circle(25f);
    var circle2 = new Circle(50f);