Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c# - Should we always include a default constructor in the class?

I have been asked this question by a colleague that should we always include a default constructor in a class? If so, why? If no, why not?

Example

public class Foo {

    Foo() { }

    Foo(int x, int y) {
        ...
    } 

}

I am also interested to get some lights on this from experts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to keep in mind that if you don't provide an overloaded constructor, the compiler will generate a default constructor for you. That means, if you just have

public class Foo
{ 
} 

The compiler will generate this as:

public class Foo
{ 
    public Foo() { }  
} 

However, as soon as you add the other constructor

public class Foo
{ 
    public Foo(int x, int y)
    { 
        // ... 
    }  
} 

The compiler will no longer automatically generate the default constructor for you. If the class was already being used in other code which relied on the presence of a default constructor, Foo f = new Foo();, that code would now break.

If you don't want someone to be able to initialize the class without providing data you should create a default constructor which is private to be explicit about the fact that you are preventing instances from being constructed with no input data.

There are times, however, when it is necessary to provide a default constructor (whether public or private). As was previously mentioned, some types of serialization require a default constructor. There are also times when a class has multiple parameterized constructors but also requires "lower level" initialization, in which case a private default constructor can be used which is chained in from the parameterized constructors.

public class Foo
{
   private Foo()
   {
      // do some low level initialization here
   }

   public Foo(int x, int y)
      : this()
   {
      // ...
   }

   public Foo(int x, int y, int z)
      : this()
   {
      // ...
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...