A default constructor is a parameterless constructor supplied automatically when a type declares no constructor, or declared explicitly by the programmer. Declaring any constructor prevents C# from adding one automatically; a constructor with an optional parameter still is not a default constructor. section 7.1 section 5.2.1
Default constructors matter when object creation is controlled by frameworks or language constraints:
- Reflection-based libraries may search for a parameterless constructor and throw if they cannot find one. section 7.1
- Generic constraints such as where T : new() require a type with an accessible default constructor. section 7.1
- Dependency injection commonly favors one constructor containing all injected dependencies, even when that means no default constructor exists. section 7.1
Dependency injection and optional parameters
BasicStopwatch(ISystemClock? systemClock = null) accepts an optional dependency and falls back to SystemClock, but it does not become a default constructor. A library or generic constraint looking specifically for a parameterless constructor cannot use it. Tests instead pass TestSystemClock directly, avoiding Thread.Sleep and making elapsed time deterministic. section 7.1
Listing 7.5 BasicStopwatch, ISystemClock, and DateTimeOffset
public class BasicStopwatch
{
private static readonly ISystemClock DefaultClock = #1
new SystemClock();
private DateTimeOffset? _startTime;
private DateTimeOffset? _stopTime;
private readonly ISystemClock _clock; #2
public BasicStopwatch(ISystemClock? systemClock = null)
{
_clock = systemClock ?? DefaultClock; #3
}
public void Start()
{
_startTime = _clock.UtcNow; #4
_stopTime = null;
}
public void Stop()
{
if (_startTime != null)
{
_stopTime = _clock.UtcNow;
}
}
public TimeSpan? ElapsedTime
{
get
{
if (_startTime != null && _stopTime != null)
{
return _stopTime - _startTime; #5
}
return null;
}
}
}
Inspect the stopwatch constructor, its optional clock parameter, and the fallback implementation used when no clock is supplied. section 7.1
Listing 5.6 Creating a new Book object without shorthand
Book book = new Book(); book.Title = ".NET in Action"; database.Add(book);
Compare explicit construction with property assignment: new Book() uses the automatically available parameterless constructor before setting Title. section 5.2.1


