This statement after the constructor arguments

I saw this block of code when I tried to create something with APN. Can someone explain to me what the "this" instructions do there?

public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings) : this(pushChannelFactory, channelSettings, default(IPushServiceSettings)) 

What are the default values ​​for these arguments?

+8
constructor c #
source share
3 answers

this calls the overloaded constructor of the ApplePushService class with the specified parameters.

for example

 // Set a default value for arg2 without having to call that constructor public class A(int arg1) : this(arg1, 1) { } public class A(int arg1, int arg2) { } 

This allows you to call one constructor, which may call another.

+9
source share

Of course, these are chains from one constructor to another. There are two forms - this for binding to another constructor in the same class and base for binding to another constructor of the base class. The body of the constructor you are hooking is executed, and then the body of your constructor is executed. (Of course, another constructor may grab onto another one first.)

If you do not specify anything, it is automatically bound to the constructor without parameters in the base class. So:

 public Foo(int x) { // Presumably use x here } 

equivalently

 public Foo(int x) : base() { // Presumably use x here } 

Note that instance variable initializers are executed before another constructor is called.

Surprisingly, the C # compiler does not detect that you will end up with mutual recursion, so this code is valid, but will end up with a stack overflow:

 public class Broken { public Broken() : this("Whoops") { } public Broken(string error) : this() { } } 

(However, this prevents you from binding to the same constructor signature.)

See my article on the constructor chain for more details.

+9
source share

This is a call to another constructor in this case : this(...) used to call another constructor in this class.

For example:

 public ClassName() : this("abc") { } public ClassName(string name) { } 

EDIT:

Is it like default values of those arguments ?

This is an overload that you can delegate to it the full logic in one place and call the rest of the constructors with default values.

You can use the keyword in these contexts.

this :

  • Calling other constructors.
  • Pass the current object as a parameter.
  • Refer to instance methods or fields.
+3
source share

All Articles