In simple words, variables that hold its own data is known as a 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);
OutputFigure 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 would we like to add? Use a data type, such as:
Int?=null;
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 Types VariablesThe variable that hold 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.
String name=null;Reference types work on the heap whereas valiue types work on the stack.
In reference types when one variable is changed then the second is also changed whereas in value types only that variable is changed that is changed by us in the runtime.