views:

123

answers:

3

Hi Why in C# 3.0, when we overload constructor of a specified class, we should write default constructor in class body? As far as I know, It was no need to do so.

class Test
{
      public int ID {get; private set;}
      public int Name {get; private set;}

      public Test() 
      {
      }

      public Test(int id, int name)
      {
           ....
      }

}    

Thank you

A: 

IF your class is useful (iow you are providing some sane defaults), then a default constructor is good, else it just creates more work and ambiguity for the user of the class.

As per your example, it is pretty useless, as you dont have access to the setters (unless your class behaves with the defaults).

leppie
+1  A: 

For when the class is being serialized - your class cannot be "rehydrated" unless it has a default constructor.

An example of this is when your class is being used in messages to/from a webservice, or when it is being saved into some sort of storage like a database table or a file.

slugster
This is the case with the `XmlSerializer`, but not the `DataContractSerializer` in .NET 3.5 which is more powerful (you can serialise private properties and fields) but less flexible in the format of the XML it handles/produces.
Andy Shellam
The BinaryFormatter also have no issues without a default constructor.
leppie
+2  A: 

Let me turn your question around: Why don't I have to write a single constructor for my class to be usable?

The reason for this is that the C# compiler will emit the default constructor for you when you don't write any constructors. Just to make it easier for us. However, when you specify one or more constructors, the C# compiler assumes you specified all needed constructors. In that case it can't possibly emit the default constructor, because not all classes should have a default constructor.

While this C# feature is nice for application developers, for framework developers it can be annoying. Some teams at Microsoft always write the default constructor in their C# code, because when a class has no (code written) constructor, it’s easy to make the mistake of adding an alternative constructor in the next release, without explicitly specifying the default constructor. In that case the new release would be incompatible, because the default constructor would be missing.

Steven