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
- int x = 20;
- int y = 10;
- Console.Write("Here X is :{0} & Y is {1}:",x,y);
- Console.Write("\n\nAfter Some Code of Lines...");
- x = y;
- Console.Write("\n\nNow X is:{0},& Y is:{1}", x, y);
-
- y = 2;
- Console.Write("\n\nAnd then X is:{0},& Y is:{1}", x, y);
Output
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,
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.
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.