2

hello I came from the world of c/c++, I have the following snippet of the code, is it good idea to initialize button this way? thanks in advance

private Button initializeButton() {
    Button button = new Button();

    button.FlatStyle = System.Windows.Forms.FlatStyle.System;
    button.Location = new System.Drawing.Point(16, 16);
    button.Name = "button";
    button.Size = new System.Drawing.Size(168, 24);
    button.TabIndex = 5;
    button.Text = "button";

    return button;
}
geek
  • 2,677
  • 4
  • 23
  • 21

2 Answers2

4

Yes, and if you want to make it shorter you can use something like this:

    private Button initializeButton() {
        return new Button() {
            FlatStyle = System.Windows.Forms.FlatStyle.System,
            Name = "button",
            ....
        };
    }

You might need to dispose this button later if you don't add it parent's Controls collection.

Community
  • 1
  • 1
Dmitry
  • 17,078
  • 2
  • 44
  • 70
3

There is nothing wrong with this at all. But, you can use a shortcut syntax too:

return new Button {
    FlatStyle = System.Windows.Forms.FlatStyle.System,
    Location = new System.Drawing.Point(16, 16),
    Name = "button",
    Size = new System.Drawing.Size(168, 24),
    TabIndex = 5,
    Text = "button"
};
Daniel Wolfe
  • 662
  • 1
  • 8
  • 19