When I was working with XmlDOM
in Asp.Net, there was a pattern like this : `XmlReader reader = XmlReader.Create()".
And then I encountered the same pattern several times later.
I like to know what's the difference between Static Constructor and "new ClassName()" Constructor (I am not sure if I am using right terms to describe what I mean).
I am not asking what XmlReader.Create()
does, what I want to learn is why I would use static constructor over than ? What kind of aspect would it provide ? What are the things I can do with static constructor but I can't do with new keyword constructor.
Thanks in advance.
First of all, let's get terminology in order.
XmlReader.Create
is not a static constructor. It's just a static method that (typically) returns new instances of objects; this is normally called "factory method". A "static constructor" would be a constructor declared with keywordstatic
, used to initialize static members of the class:Now as to why a factory method may be preferable. There can be several reasons.
For one, a constructor (invoked via
new
) always has to either provide a newly instantiated object, or throw an exception. A factory method can returnnull
if that makes sense, or it may maintain some cache of objects, and avoid creating a new one all the time (e.g. when objects are immutable).Another reason is that when you do
new T()
, you always get specifically an instance ofT
. A factory method could instead create an instance of some subclass ofT
, depending on input parameters and other factors. In case ofXmlReader
, this is precisely what happens -XmlReader
itself isabstract
, so there cannot be any instances of it; however, there are several subclasses that serve different purposes (validating/non-validating, stream backend / DOM backed, etc), andXmlReader.Create
picks the right one based on overload and arguments you supply to it.