Initializing Fields in Place


C# enables you to initialize fields in place. This means that you can tell the compiler to automatically set a field to a certain value whenever someone creates an instance of the class. By default, the .NET Framework sets uninitialized fields to zero if they are numeric, false if they are Boolean, or null if they are reference types (like string or any variable of class you declare).

To add field initializers:

  • After a field declaration, set the field equal to a literal value or to a function ( Figure 2.68 ).

    Figure 2.68 Fields can be initialized in place. They can be set to a literal value, to a new object or to the result of a static function. In the case of the ToDoList class, every time we create an instance of ToDoList we also create an instance of the HashTable class, if we didn't, then list would be null every time we created a ToDoList.
     class ToDoItem {    string item  = ""  ;    string description  = ""  ; } class ToDoList {    Hashtable list =  new Hashtable  (); } 

graphics/tick.gif Tip

  • You can set field initializers to literal values, to the result of static functions, to static fields, or to the result of an instance function if it is called through a static field. Static functions and fields will be covered in Chapter 6, "Special Members."




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