As a “javaland” programmer I’m used to Factory Methods and Multiple Constructors.
My main uses for factory patterns are to delay decisions until runtime, perform some kind of side effect or restriction during the instantiation or hide the concrete type.
As I dig into C# I see more and more APIs that mix multiple constructor and static Create methods.
E.g., XmlReader and XmlTextReader. XmlWriter and XmlTextWriter.
My questions are:
- Is there something special with
Createmethods or it is just a convention (like java:getInstance)? - What are the good practices in C# regarding factory methods vs constructors? Why, for example, there are several
Createmethods that acceptsXmlWriterSettingsarguments inXmlWriterand no constructor inXmlTextWriterwith the same purpose? And, in the other hand, why only constructors acceptsEncodingarguments? - I guess the main question is, in idiomatic C#, when is it recommended to expose factory methods and when should public constructors be exposed?
1) The only difference I know of is that generic type inference is supported for methods but not for constructors. Therefore, you can write:
While if you wanted to use a constructor (unfortunately
Tupledoes not have a public constructor, so the example won’t compile) you would have to write:Of course this only applies to constructors of generic types, so it’s not exactly a mainstream difference.
2) I suspect that was kind of a “random” (if “random” sounds harsh, then let’s say “not made with best practices foremost in mind”) decision, but I don’t have any data to back this up.
3) Factory methods are also the only way you can return an object cast as one of its ancestor types. Sometimes this is not only desirable but also necessary because the user of your type might not know what type they are supposed to construct. For example, consider a factory method that returns a
Streamwhich might be either aRedStreamor aBlueStream, depending on some input parameters.