When I create a new Windows Form, Visual Studio automatically provides me with two files:
MyForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Hardest_Game
{
public partial class MyForm : Form
{
public MyForm()
{
InitializeComponent();
}
}
}
MyForm.Designer.cs
namespace Hardest_Game
{
partial class MyForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "MyForm";
}
#endregion
}
}
My first question is, why are we creating two files? Why not just define the methods in one file?
Second question, and the more important one, why are we using System.ComponentModel.Icontainer
here, with all the Dispose()
methods and such?
What do they actually do, msdn.microsoft.com doesn't provide too much information, it simply explains that they're used to contain stuff.
This code seems to work just fine:
using System.Windows.Forms;
using System.Drawing;
namespace Hardest_Game
{
class MainWindow : Form
{
public MainWindow()
{
this.InitializeComponent();
}
// Controls
Button myButton { set; get; }
void InitializeComponent()
{
myButton = new Button();
myButton.Text = "My Button";
this.Controls.Add(myButton);
}
}
}
It looks cleaner, it uses less stuff, etc. Why would I use the method Microsoft wants me to use?
EDIT: Okay sorry guys, my second question might not have been the best one, let me try again: If I were to programmatically create a program (as I do in the third piece of code), including all of its UI etc, would I benefit from using IContainer
and Dispose()
? That's why I asked what's the purpose of them, to know if I should use them myself, or if they're only for the autogenerated code.