Why in C# 3.0, when we overload constructor of a specified class, we should write default constructor in class body?

StackOverflow https://stackoverflow.com/questions/2628617

Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top