Friday, September 21, 2012

In C# Everything is an Object

I assume you read the document and had a basic concept on Object & Class. So how about I told you that everything you drag from the toolbox into the Form creates an object.

For example lets talk about the Button control.

When you drag a button into the Form, you create an instance of the (Button) class. Button class contains some field for the button object and also have some methods. So how you place values in those fields and interact with those method? You already did in the previous examples. When you write (textBox1.Text = "name") you just set a value for the field (public string Text) in the Button class to a string "name". Again when you write (textBox1.Clear();) it just called the method (public void Clear()) and clears everything from the textBox1.

When you create an object you always have to initialize it to work with it in the application. To initialize an object all you have to do is to write:
                                                 
                                                                new ClassName();

For example:

When you drag a button it just create the object like: Button button1;
But when you start debugging the  InitializeComponent(); method initialize the button1 object like this:

this.button1 = new System.Windows.Forms.Button();

To see this initialization double click on the Form1.Designer.cs and go to the (Windows Form Designer Generated Code) region and expand it. You will find the InitializeComponent(); method under which the command this.button1 = new System.Windows.Forms.Button(); is generated.

So if you delete the InitializeComponent(); line from the Form1.cs
you would end up with a blank Form. Cause the program will only create a button1 object it will not initialize it. Due to this it will be swapped away from the memory. This is called Object Life Cycle. That is after a object initialization it does the work given to it and when it finished it just die. 

So experiment with the controls and drag and drop as much as you can into the form. At each time you will create an object and at debugging you will initialize it by the InitializeComponent(); method.

NOTE: We use (.) dot after an object to interact with their fields and methods.
Field and Variable are not same. Fields are declared at the top of the Class and if a field is inside of a Method we call it Variable.

No comments:

Post a Comment