yolo sora
yolo sora

Reputation: 442

Property initialization before constructor execution

I am using an object initializer to create an object with a Position property like this:

var control = new HtmlTextbox(browser)
{
    Position = position;
};

As I know it's the same as:

var control = new HtmlTextbox(browser);
control.Position = position;

But I want to use initializated Position property in my constructor method. Is there any way to do it without providing the Position as an argument for constructor?

Upvotes: 3

Views: 4325

Answers (2)

jnhecate
jnhecate

Reputation: 11

Another way you can approach this is using inheritance and initialize the value from there, as the most-derived class' constructor gets called last, but its values are initialized first.

Upvotes: 0

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

What you want to achieve is not possible.

It seems to me you want to make some parameters to the constructor optional. You may want to look into this pattern:

//Your constructor
public HtmlTextbox(TextboxConfiguration config)
{
    //config.Position
}

//A Transfer class
public class TextboxConfiguration
{
    public T Browser { get; set; }
    public T Position { get; set; }
}

//Your code
var config = new TextboxConfiguration
{
    Browser = browser;
    Position = position;
}
var textbox = new HtmlTextbox(config);

Upvotes: 5

Related Questions