Variables, Stack, Heap and default values in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 3188 red flag

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read Multidimensional Arrays in C# before this article.

Introduction

So far, we have discussed the multidimensional arrays in C#. Now let's see about variables and some memory elements of C# in this chapter.

Objective

The main objective of this article is to learn about variables, stack, heap, definite assignment and default values of C# programming.

Variables

Variable represents a storage location of the memory that contains a modifiable value (data which can be changeable).
It can be a parameter (value, out or ref), local variable (described locally), field (static or instance), or an array element.

                                   

Stack and Heap

Stack and Heap are the important parts of the memory where variables reside in.

Stack:
  • It is a block of memory which stores local variables and parameters.
  • The important logic of the stack is that it grows with the entry of the function and shrinks again when it is exited.
  • Let's take an example code,
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Man
    {
        class Program
        {
            static int Main(int a)
            {
                if (a == 0)
                    return 1;
                return a + Main(a + 1);
            }
        }
    }
    The above method is the recursive method, which means the method calling itself. So, for every entry of the method, a new int is allocated on the stack and deallocated after its exit.
Heap:
  • Heap is a block of memory which is derived to store objects (means reference type instances).
  • When a new object is created in a method, it is stored (allocated) on the heap and returns a reference to that object.
  • Objects created are gets filled on the heap during the execution of the program.
  • Runtime contains a Garbage Collector which deallocates (removes) the objects simultaneously. Hence, the memory is cleared, which means our computer does not run out of the memory.
  • Lets take an example code.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Man
    {
        class Program
        {
            static void Main()
            {
                StringBuilder strb1 = new StringBuilder("Obj1");
    
                Console.WriteLine(strb1);  // Prints Obj1
    
                StringBuilder strb2 = new StringBuilder("Obj2");
                StringBuilder strb3 = strb2;
    
                Console.WriteLine(strb3);  // Prints Obj2
            }
        }
    }
    
    In the above code, we have created three StringBuilder objects srtb1, strb2 and strb3.
  • First StringBuilder object "Obj1" is referenced by strb1 which has immediate eligible for Garbage Collection, because no other method or object is using it.
  • And we also have strb2 which is accessed by strb3. Hence it doesn't become eligible for collection until we finish the usage of strb3.
  • The output of the above code will be,

  • Value type instances are active at the place where variable was declared.
  • If any instance that declared as a field of an object (or an array element), that instance lives (remains active) on the heap.
  • Heap also has the ability to store constants and static fields.

Note: We cannot delete the objects in C# explicitly as we do in C++.

Definite Assignment

C# enforces the definite assignment policy. This means, it is impossible to access the unallocated (or uninitialized) memory from the outside.
Definite assignment policy has three implications, which are,
  1. Local variables must have been assigned a value before they can be read.
  2. When a method is called, Function arguments must be supplied.
  3. Other elements such as array elements and fields are automatically initialized by the runtime.

Default Values

In C#, all the type instances have the default values which results as bitwise zeroing of the memory.
  • For all reference types - null
  • For all numeric and enum types - 0
  • For bool type - false
  • For char type - '\0'
In order to obtain the default value for any type, we have to use the default keyword.

Conclusion

In this article, we have seen what is variable and memory elements of C#. Hope you understood the article.

Thanks for reading.

Regards,
Krishna.

Recommendation
Read Parameters, ref and out modifiers in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)