
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
162
|
Chapter 3: Classes and Structures
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<T>
where T: System.IO.TextWriter
{
public Log(T logStream)
{
this.logStream = logStream;
}
private T logStream = null;
public T LogStream
{
get {return (logStream);}
set {logStream = value;}
}
// use the LogStream field...
public void Write(string text)
{
logStream.Write(text);
}
}
When a client creates an object from this class, the client is forced to initialize the
LogStream field.
Discussion
There is a small problem with not supplying a default constructor. If a class inherits
from
Log<T> and does not supply a constructor of its own, the C# compiler will pro-
duce the rather cryptic error “No overload for method ‘Log’ takes’ ‘0’ arguments.”
The following class produces this error:
public class EnhancedLog<T> : Log<T>
where T : System.IO.TextWriter
{
public EnhancedLog (T logStream)
{
// Initialize...
}
}
What this means is that Log<T> does not contain a default constructor. The C# com-
piler automatically adds a call to the base