Until C# 3.0, the only real solution to this was to write
one or more factory methods. These are described in
the sidebar below. But now we have another option.
Factory Methods
A factory method is a static method that
builds a new object. There’s no formal support for this in C#, it’s just
a common solution to a problem—a pattern, as popular idioms are often
called in programming. We can get around the overload ambiguity problems
by providing factory methods with different names. And the names can
make it clear how we’re initializing the instance:
public static PolarPoint3D FromDistanceAndAngle(
double distance, double angle)
{
return new PolarPoint3D(distance, angle, 0);
}
public static PolarPoint3D FromAngleAndAltitude(
double angle, double altitude)
{
return new PolarPoint3D(0, angle, altitude);
}
We rather like this approach, although some people frown on it as
insufficiently discoverable. (Most developers
aren’t expecting to find static methods that act rather like
constructors, and if nobody finds these methods, we’re wasting our time
in providing them.) However, this pattern is used all over the .NET
Framework libraries—DateTime, TimeSpan, and Color are popular types that all use this
technique.
You are currently reading a PREVIEW of this book.
Get instant access to over
$1 million worth of books and videos.