Adding Constructors


Constructors are functions that are triggered automatically when an object is created. You can also use constructors to require the developer using the class to set initial values for the class. For example, with a Checking class it makes sense to require a developer to set the initial balance for the account. You can have more than one constructor by using method overloading, a technique discussed earlier in this chapter.

To add a constructor:

  1. Add a function to your class that doesn't have a return type and is named the same as the class name ( Figure 6.10 ).

    Figure 6.10 Constructors are usually used to initialize values. In this case Balance is being initialized to 100.
     class Account {    int Balance;  public Account()   {   Balance=100;   }  } 
  2. Change the scope of the constructor by adding one of the scope modifiers: public, private, protected, internal or protected internal. (Constructors are private by default.)

  3. When using the new operator to create an object, pass the parameters for the constructor in parentheses after the class name ( Figure 6.11 ).

    Figure 6.11 Balance has only one constructor and it has a parameter called InitialBalance. This means that when you create an Account you have to pass in a value for initial balanceit isn't optional.
     class Account {    int Balance;    public Account(int InitialBalance)    {        Balance = InitialBalance;    } } class Bank {    void OpenAccount()    {       Account acct =  new Account(100)  ;    } } 

graphics/tick.gif Tips

  • If you don't add a constructor to your class, the compiler will add a default constructor automatically.

  • If you add a constructor, the compiler doesn't add a default constructor. That means that if you add a single constructor that accepts a parameter (like in Figure 6.10 ), the only way to create an instance of the class is to pass the parameter in the new operator. This is a good technique to use if you want to require developers to pass a value whenever they create an object of the type.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net