Initializers

If you know that certain member variables should always have the same value when the object is created, you can initialize the values of these member variables in an initializer, instead of having to do so in the constructor. You create an initializer by assigning an initial value to a class member:

private int Second = 30; // initializer

Suppose that, for whatever reason, the boxes you’re creating in your program are always 6 inches high. You might rewrite your Box class to use an initializer so that the value of height is always initialized, as shown in bold in Example 7-4.

Example 7-4. You use an initializer to set the value of a member variable within the class itself, so you don’t need to do it in the constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_7_4_ _ _ _Initializer
{
   public class Box
   {
      // private variables
      private int length;
      private int width;
      private int height = 6;

      // public methods
      public void DisplayBox( )
      {
         Console.WriteLine("Length: {0}, Width: {1}, Height: {2}",
                           length, width, height);
      }

      // constructor
      public Box(int theLength, int theWidth)
      {
         length = theLength;
         width = theWidth;
      }
   }

   public class Tester
   {
      static void Main( )
      {
         Box boxObject = new Box(4, 8);
         boxObject.DisplayBox( );
      }
   }
}

The output looks like this:

Length: 4, Width: 8, Height: 6

If you do not provide a specific initializer, the constructor initializes each integer member variable to zero (0). In the case shown, however, ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.