c# - base() and this() constructors best practices -


I am in what position: base () and: this () constructor is the parentheses of my constructor (or even In other places in the code) Where are these good exercises and when are mandatory?

: base (...)

If you leave the call to a base constructor, it will call the default base constructor automatically.

If there is no original constructor, then it is mandatory to explicitly call the Base Constructor.

Even if there is a default constructor then you may still want to call a different constructor than the default constructor. In this case you still want to use the base (foo, bar) to call a different constructor than the base constructor.

I want to call it the base code default constructor, but when you like to see clearly, I do not have a bad practice to leave it base () Assuming there is no harm in involving it. This is a matter of taste.

: This (...)

This syntax allows you to call a constructor the same class With the second signature from the second. It is not mandatory to do this, but can sometimes be useful.

This can be useful when used to reuse general code in consultants. For example C # 3.5 or earlier you can simulate optional parameters on a constructor:

  fu (int x, int y) {this.x = x; this. Y = y; } Foo (int x): This is now available with the basic default (<, c, 10) {} / y 10 default  

C # 4.0 optional parameters which reduce the need for this approach gives.

An alternative way to reuse code in constructors is to identify it in a fixed function which is called it from every constructor, which it has to use.


Comments