Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't access constructor in body of another constructor?

Tags:

c#

constructor

I know that i can access constructor on another constructor like below but is there a way to access it in body of constructor ?

public Rectangle(int size) : this(size, size)
{
    Console.WriteLine("Square Constructor Called");
    //this(size,size); i want to access like this 
}
like image 990
Freshblood Avatar asked Dec 03 '22 04:12

Freshblood


2 Answers

You can't do that. The full justification is here, but in summary:

In short, achieving the desired construction control flow is easy to do without adding the [the ability to call base constructors in arbitrary locations], and there's no compelling benefit to adding the feature. No new interesting representational power is added to the language.

like image 195
Greg Beech Avatar answered Jan 18 '23 23:01

Greg Beech


Constructors can only chain once, basically - which has to be specified before the body of the constructor itself.

Normally the solution to wanting to chain to multiple constructors is to have one "master" constructor which all other constructors chain to eventually, and which does everything you could want.

like image 44
Jon Skeet Avatar answered Jan 19 '23 01:01

Jon Skeet