Value Type And Reference Type Variables

In this article we will learn about Value Type and Reference Type variables.

In simple words, variables that hold their own data are known as value type variables and the variables that are of this type are listed below.

  • All numeric data types, such as byte, short, integer, long, float and double.
  • Also boolean, char and date time.
Source Code
  1. int x = 20;  
  2. int y = 10;  
  3. Console.Write("Here X is :{0}  & Y is {1}:",x,y);  
  4. Console.Write("\n\nAfter Some Code of Lines...");  
  5.             x = y;  
  6. Console.Write("\n\nNow X is:{0},& Y is:{1}", x, y);  
  7. //here if i change X then Y remains constant that is 10;  
  8.             y = 2;  
  9. Console.Write("\n\nAnd then X is:{0},& Y is:{1}", x, y);
Output
 
Value Types and Reference Types Variables
Figure 1: Output

In other words, we can say that when a varible is declared using basic, built-in data types or a user-defined structure it is known as a value type. It stores its contents (value) in memory allocated in the stack.

If value type variables can’t become nullable then if we want to null them, then what should we add? Use a data type, such as,
  1. Int?=null;  
  2. Short?=null;  
Only strings can be null (by default).

All data types are derived from the System.valuetype class.

Value types work by copying the orignal so we can say that it is a slow process.

Reference Type Variables


The variable that holds the address of another location instead of the data is called a reference type variable. It includes the following:
  • Object
  • Class
  • Interface
  • Delegates
  • Array
When we initialize the value to a variable it creates a heap in memory and stores its address in itself.

You know that a string is itself an array and a string is nullable by default.
  1. String name=null;  
Reference types work on the heap whereas value types work on the stack.

In reference types when one variable is changed then the second is also changed; whereas in value types the only variable that is changed is changed by us in runtime.