Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 282
yolo sora Avatar asked Nov 04 '25 11:11

yolo sora


1 Answers

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);
like image 155
Christian Gollhardt Avatar answered Nov 07 '25 05:11

Christian Gollhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!