2 years ago

#66590

test-img

Jay

Why can I have a parameterless constructor and a constructor with only default parameters

Background

I'm working with unity which seems to be serialising classes using some parameterless constructors it creates.

The following code did not properly initialise values:

public WarmthProvider(float initialWarmth = 1)
{
    this.warmth = initialWarmth;
}

My solution looks like this:

public WarmthProvider(float initialWarmth)
{
    this.warmth = initialWarmth;
} 

public WarmthProvider() : this(1)
{

}

(no, this is not in a monobehaviour class)

Question

When implementing this, I noticed the following was perfectly legal and compiled:

public WarmthProvider(float initialWarmth = 1)
{
    this.warmth = initialWarmth;
} 

public WarmthProvider() : this(1)
{

}

Why is this possibly allowed? Surely this is ambiguous as to which constructor to call? Do these not now have the same signature? Is there any reason allowing this syntax is better than it being illegal?

c#

constructor

default-constructor

0 Answers

Your Answer

Accepted video resources