Lecture overview -- Keyboard shortcut: 'u'  Previous page: Initialization of objects -- Keyboard shortcut: 'p'  Next page: Copy constructors -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home  Page 27 : 29
Object-oriented Programming in C#
Classes and Objects
Constructors in C#

You should strive to organize initialization of all instance variables in constructors.

A constructor is a special method which is called automatically in order to initialize a new instance of a class

  • Constructors in C#

    • Have the same name as the surrounding class

    • Do not specify any return value type

    • Are often overloaded - several different constructors can appear in a class

    • May - in a special way - delegate the initialization job to another constructor

    • In case no constructors are defined, there is a parameterless default constructor

      • As its only action, it calls the parameterless constructor in the superclass

    • In case a constructor is defined there will be no parameterless default constructor

/user/normark/oop-csharp-1/sources/c-sharp/bank-account/bank-account-0/bank-account.csConstructors in class BankAccount. This program is explained

The naive implementation of three constructors.

/user/normark/oop-csharp-1/sources/c-sharp/bank-account/bank-account-0a/bank-account.csImproved constructors in class BankAccount. This program is explained

A much better implementation of the three constructors.

/user/normark/oop-csharp-1/sources/c-sharp/Die-variants/die-0/die.csConstructors in the class Die. This program is explained

Two constructors in class Die. One constructor uses the other (general) constructor.

Read more about constructors in C# in the text book version of this material.