ARTICLE

Memory allocation using new operator in C#

Posted by Sourav Kayal Articles | Articles C# June 29, 2013
This article presents some interesting facts of the new operator in C#.
Reader Level:

This article presents some interesting facts of the new operator in C#. This is part 2 of the Look Under the Hood Series.

Dear friend, how are you? I am fine though a little busy with my MCA final semester exam. Anyway let's start our journey of "Under the Hood Concepts". Here is my Series-1. This article presents a practical explanation of how the new operator works in the C# .NET environment. And I know the new operator is not new to developers. (Why new? You did not use in C++ to create objects?) Yes, the new operator creates objects of a class. Object or Instance?? There is a little confusion about what objects and instances are, right?

Let's clear clarify Objects and Instances

My little experience says that this first confusion exists when people start learning Object Oriented Programming. I too was among them. I asked my teacher "Sir! What is the difference between an object and an instance?" And he replied "An instance is something that is waiting to be an object of a class".

Then, I began to determine the exact difference between them. Let me explain in my way.

Instance: An instance is a generic thing (I will not say generic object to define a generic thing because you may say I am using object to define instance, Ha Ha...) that will be transformed into an object if we set some property to it.

Object: An object is something that holds it's own property and own behavior.

I know you are not satisfied with this rubbish definition. Then let me use my last weapon (Ha Ha...). Yes let's understand with an example. Have you used LINUX or UNIX in your college lab?

If yes then read few more line and you will clearly understand objects and instances. Let us consider a UNIX server as my Class. And all the computers in the lab are accessing the same server. The cursor in the login screen is blinking in all the computers but no one (no student) has entered their username and password because they don't know the username and password and they are waiting for the system admin. Now, if there are 60 computers in the lab (in our lab it's 60) then we have created 60 instances of the Class (here UNIX OS).

Now after a while the Admin comes and announces that the system username is their name and their password is their roll number. Immediately all students login to the system and I am observing my friend, who is in my right chair, has set his font color to Red and left the chair as Green. Hmm. They are customizing thier environment. And when they are customizing thier terminal with their own property each and every terminal is transforming to an object.

I think now you are clear with object and instance. Now let's proceed with our discussion.

How memory get allocate using new operator?

Yes, the new operator creates objects of a specified class. Here is my code, I have defined one class and I have created just instance of the class. And in the IL code you will see there is no sign of the object anywhere in the IL code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class
Test
    {
    } 
    class
Program
    {
        static void Main(string[] args)
        {
            Test t = null;
            Test t1;
        }
    }
}

Here is the IL code.

image1.jpg

Now let's use the new operator and see the change.

The following is my C# code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class Test
    {
    } 
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
        }
    }

}

And the IL output is here.

image2.jpg

We can see very clearly that the new object has created one object of my Test class. Now after reading to this point if you draw the conclusion in your mind "Ok , I understood that the 'new' operator allocates memory" then you are partially wrong. Let's get to the next point.

New operator always does not allocate memory

Yes, what you read just now is correct , let me show an example. Here I have created an array and have used the new operator to allocate memory for 10 elements. The following is my C# code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class
Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[10];
        }
    }
}


And here is my IL output.

image3.jpg

We can see clearly that no memory allocation has occured in spite of using the new operator. Then when will the memory be allocated? The answer is "when we use it in an array in our program". Actually the .NET code optimizer is very smart when it sees that there is no use of an array in the current program, it simply omits the array from being processed. Is it really? Hmm, are you not believing me? Look at the next screen.

Here is my program in which I have declared an array and just made a little operation on it. As in the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class
Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[10];
            a[0] = 100;
        }
    }
}


And have a look at the IL screen.

image4.jpg

We can see the array (array name a) has been created in a local variable creation section.

A very interesting fact of the new operator

The interesting fact of the new operator is, when we use the new operator to create an object (if the .NET code optimizer thinks it is really needed) of a particular data type then the initialization operation is also done with that . How?

Here I have created one integer variable "a" using the new operator (Have you ever found such a mad programmer that creates an integer variable using the new operator?) And without initializing it I want to print it's value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class
Program
    {
        static void Main(string[] args)
        {
            int a = new int();
            Console.Write("Local variable a:- "+ a +"\n");
            Console.ReadLine();
        }
    }
}

This is the output screen.

image5.jpg

See, we do not set the value 0 to the variable "a" but it's showing the value of the variable "a" is 0. But if we try without using the new operator as in the following:

class Program
{
     static void Main(string[] args)
     {
          int a;
          Console.Write("Local variable a:- "+ a +"\n");
          Console.ReadLine();
     }
}

Hmm. Error. Use of unassigned local variable "a".

image6.jpg

So the concept is that when we use the new operator to create memory then the memory is created and by default an appropriate value is set. Here the data type is integer so by default 0 has been assigned here. If your data type is string then it will be bull by default. OK, Sourav! This is the case of pre-defined data types; what about user-defined data types like class?

It's very similar to pre-defined data types. Each and every member will be assigned an appropriate value, as in the following example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class
Test
    {
       public Int32 Roll;
       public String name;
    }
    class
Program
    {
        static void Main(string[] args)
        {
            int a = new int();
            Console.Write("Local variable a:- "+ a +"\n"); 
            Test t = new Test();
            Console.Write("String class member:- "+  t.name + "\n");
            Console.Write("Integer class member:- " +  t.Roll +"\n");
            Console.ReadLine();
        }
    }
}

Here is the output

image7.jpg

The String class member is blank because it's null.

Conclusion: Here I have tried to represent the actual purpose of the new operator with an example and of course in my style. If you people like it then please leave your valuable comments below.

COMMENT USING