Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

3.21. Preventing the Creation of an Only Partially Initialized Object

Problem

You need to force a client to use an overloaded constructor, which accepts parameters to fully initialize the object, rather than a default constructor, which may not fully initialize the object. Often a default constructor cannot fully initialize an object since it may not have the necessary information to do it. Using a default constructor, the client is required to perform a multistep process; for instance, create the object and then initialize its fields either through various properties and/or methods.

Solution

By removing the default constructor and strictly using parameterized constructors, the client is forced to provide the necessary initialization parameters during object creation. The following Log class will not initialize its LogStream field to a StreamWriter object on construction:

public class Log
{
    private StreamWriter logStream = null;

    public StreamWriter LogStream
    {
        get {return (logStream);}
        set {logStream = value;}
    }

    // use the LogStream field...
    public void Write(string text)
    {
        logStream.Write(text);
    }
}

The C# compiler will automatically create a default constructor that calls the default constructor of its base class, if you omit the constructor for a class. The following modified class will prevent the default constructor from being created:

public class Log
{
    public Log(StreamWriter logStream)
               {
               this.logStream = logStream;
               } private StreamWriter logStream = null; public StreamWriter ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata