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
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Customizing constructors in C#


We want to initialize instances of the Circle class with the radius value. In order to do so, we can take advantage of the constructors in C#. Constructors are special class methods that are automatically executed when we create an instance of a given type. The runtime executes the code within the constructor before any other code within a class.

We can define a constructor that receives the radius value as an argument and use it to initialize an attribute with the same name. We can define as many constructors as we want. Therefore, we can provide many different ways of initializing a class. In this case, we just need one constructor.

The following lines create a Circle class and define a constructor within the class body.

class Circle
{
  private double radius;

  public Circle(double radius)
  {
    Console.WriteLine(String.Format("I'm initializing a new Circle instance with a radius value of {0}.", radius));
    this.radius = radius;
  }
}

The constructor is...