Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't know what this c# pattern/structure/code is called

I've been trying to find out the name for something, but without knowning the name, I am having a hard time Googling for the answer. It's a bit of a catch 22. I was hoping that if I posted an example, someone out there might recognize it.

Basically, it's a way to initialize any number of public properties of an object, without using a constructor.

For example, if I wanted to dynamically add a text box to my winform, I could:

System.Windows.Forms.TextBox tb_FirstName = new System.Windows.Forms.TextBox()
{
    Location = new System.Drawing.Point(0, 0),
    Name = "tb_FirstName",
    Size = new System.Drawing.Size(100, 20),
    TabIndex = 1
};
frm_MyForm.Controls.Add(tb_FirstName);

Does anyone know what this is called? Furthermore, is there a reason why I should avoid doing this. I prefer how the above code reads, as opposed to individually setting properties as such:

System.Windows.Forms.TextBox tb_FirstName = new System.Windows.Forms.TextBox();
tb_FirstName.Location = new System.Drawing.Point(0, 0);
tb_FirstName.Name = "tb_FirstName";
tb_FirstName.Size = new System.Drawing.Size(100, 20);
tb_FirstName.TabIndex = 1;

frm_MyForm.Controls.Add(tb_FirstName);

Mostly, I jsut want to know the name of the first example, so that I can do a little reading on it.

like image 952
Chronicide Avatar asked Mar 18 '26 19:03

Chronicide


1 Answers

It's called an object initializer.

One potential issue with their use is when using an object initializer for an object in a using statement. If any of the property setters throws an exception, or evaluating code for the value of the property does, dispose will never be called on the object.

For example:

        using (Bling bling = new Bling{ThrowsException = "ooops"})
        {
            //Some code...
        }

An instance of Bling will be created, but because property ThrowsException throws an exception, Dispose will never be called.

like image 116
Tim Lloyd Avatar answered Mar 21 '26 09:03

Tim Lloyd