Article

Object Oriented C# for ASP.NET Developers

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Next

Constructors

A constructor is a special type of method that is invoked automatically when an object is created. Constructors allow you to specify starting values for properties, and other such initialization details.

Consider once again our Tree class; specifically, the declaration of its height field (which should now be private and accompanied by a public property):

 private int height = 0;

It's the = 0 part that concerns us here. Why should all new trees be of height zero? Using a constructor, we can let users of this class specify the initial height of the tree. Here's what it looks like:

 private int height;        
       
 public Tree(int height) {        
   if (height < 0) this.height = 0;        
   else this.height = height;        
 }

At first glance, this looks just like a normal method. There are two differences, however:

  • Constructors never return a value; thus, they don't have a return type (void, int, bool, etc.) in their declaration.
  • Constructors have the same name as the class they are used to initialize. Since we are writing the Tree class, its constructor must also be named Tree.

So dissecting this line by line, the first line states that we are declaring a public constructor that takes a single parameter and assigns its value to an integer (int) variable height. Note that this is not the object field height, as we shall see momentarily. The second line checks to see if the height variable is less than zero. If it is, we set the height field of the tree to zero (since we don't want to allow negative tree heights). If not, we assign the value of the parameter to the field.

Notice that since we have a local variable called height, we must refer to the height field of the current object as this.height. this is a special variable in C# that always refers to the object in which the current code is executing. If this confuses you (no pun intended), you could instead name the constructor's parameter something like newHeight. You'd then be able to refer to the object field simply as height.

Since the Tree class now has a constructor with a parameter, you must specify a value for that parameter when creating a new Tree:

Tree myTree = new Tree(10); // Initial height 10

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links