Creating objects of a class using C#

Now that you have understood how to create a class using C#, in this tutorial you will learn how to create objects of any class. If creating a class is the first step then creating the object of a class will be your second step when using C#.

What is an object?

By definition an object is an instance of a class. Objects are created at runtime when memory is allocated by looking at the blueprint of the class for which you are trying to create the object. For example let us say you create a class Test with just one data member of the type integer

class Test  {        public int I;    }

To create an object of this class you will write

Test t = new Test();

At runtime when the above line will get executed an object of the Test class will be created. The object will be allocated 4 bytes of memory because a 32 bit integer variable consumes 4 bytes of memory and there is only one integer type data member in this Test class. If you have 4 integer type data members in the Test class then the object of this class will consume 16 bytes of memory in the RAM.

Understanding the object creation process

As mentioned above you will be using the new keyword whenever you want to create an object of a class. If you have a class Student then to create the object of this Student class you will write

Student s = new Student();

If you have a class Football then to create its object you will write

Football f = new Football();

But more than learning the syntax for creating the object of a class you need to understand what happens in the RAM when an object is created. To understand this concept lets understand each part of the line which we use to create the object

Creating object of a class using C#
In the above image you can see an explanation for various parts of the line you write to create an object of the Test class. The most important thing to understand here is that t is a pointer and not an object. The role of new keyword is to request for memory allocation at runtime. The Test() function called at the end of this line is the constructor of the Test class which we want to call immediately after the object creation. You will learn more about constructors in coming tutorials. If you have to narrate the complete story behind the object creation then you will say

A pointer t is created in the memory and a new memory block is allocated for the object of the Test class. Then t is given the address of this object. In the end we will have a t pointer pointing to the object the Test class.

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp