X hits on this document





268 / 396

Chapter ‎18   Unsafe code

class Message { object sender; string text;

public Message(): base() {} }

10.10.5 Private constructors

When a class T declares only private instance constructors, it is not possible for classes outside the program text of T to derive from T or to directly create instances of T. Thus, if a class contains only static members and isn’t intended to be instantiated, adding an empty private instance constructor will prevent instantiation. For example:

public class Trig { private Trig() {}// Prevent instantiation

public const double PI = 3.14159265358979323846;

public static double Sin(double x) {...} public static double Cos(double x) {...} public static double Tan(double x) {...} }

The Trig class groups related methods and constants, but is not intended to be instantiated. Therefore it declares a single empty private instance constructor. At least one instance constructor must be declared to suppress the automatic generation of a default constructor.

10.10.6 Optional instance constructor parameters

The this(...) form of constructor initializer is commonly used in conjunction with overloading to implement optional instance constructor parameters. In the example

class Text { public Text(): this(0, 0, null) {}

public Text(int x, int y): this(x, y, null) {}

public Text(int x, int y, string s) { // Actual constructor implementation } }

the first two instance constructors merely provide the default values for the missing arguments. Both use a this(...) constructor initializer to invoke the third instance constructor, which actually does the work of initializing the new instance. The effect is that of optional constructor parameters:

Text t1 = new Text();// Same as Text(0, 0, null) Text t2 = new Text(5, 10);// Same as Text(5, 10, null) Text t3 = new Text(5, 20, "Hello");

10.11 Static constructors

A static constructor is a member that implements the actions required to initialize a class. Static constructors are declared using static-constructor-declarations:

static-constructor-declaration: attributesopt   static-constructor-modifiers  identifier   (   )   static-constructor-body

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.255

Document info
Document views540
Page views540
Page last viewedMon Oct 24 23:55:57 UTC 2016