views:

47

answers:

3

Hi Folks,

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.

A: 

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.Classic constructor is used to initialize instance variables, and called every time the object is created

ArsenMkrt
A: 

You can do the same in both constructors. THere is no difference. However, the static constructor is only called ONCE in the lifetime of your program and is only allowed for classes with static members. It can initialize the private static variables before using them.

Henri
"and is only allowed for classes with static members", Static constructor is allowed for any classes, with or without static members!
ArsenMkrt
+7  A: 

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 keyword static, used to initialize static members of the class:

class MyClass {
   static MyClass() { ... } // static constructor
}

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 return null 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 of T. A factory method could instead create an instance of some subclass of T, depending on input parameters and other factors. In case of XmlReader, this is precisely what happens - XmlReader itself is abstract, 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), and XmlReader.Create picks the right one based on overload and arguments you supply to it.

Pavel Minaev
Very clear answer.
Reed Copsey
Thanks, very clear and comprehensible answer I was looking for. Now it all makes sense.
Braveyard