A variable is always defined with a data type. It is a name of memory location. It is used to store data. Its value can be changed and it can be reused many times.
What are data type?
C# is a strongly typed language. It means, that you cannot use variable without data types. Data types tell the compiler that which type of data is used for processing. Such as if you want to work with string value then you will have to assign string type variable to work with.
Data Type | Size | Range |
---|---|---|
byte | unsigned 8-bit integer | 0 to 255 |
short | signed 16-bit integer | -32,768 to 32,767 |
int | signed 32 bit-integer | -2,147,483,648 to 2,147,483,647 |
long | signed 64 bit-integer | -9,223,372,036,775,808 to 9,223,372,036,775,808 |
float | 32-bit floating point with 7 digits precision | -3.402823e38 to 3.402823e38 |
double | 64-bit floating point with 15-16 digits precision | -1.79769313486232e308 to 1.79769313486232e308 |
decimal | 128-bit floating point with 28-29 digits precision | (+ or -)1.0 x 10e-28 to 7.9 x 10e28 |
char | Unicode 16-bit character | Unicode symbols used in text |
bool | Logical Boolean type | True or False |
Data types in any language are keywords used to specify the type of data stored and handled by a variable. They also decide the operations on data.
C# provides two types of data types: Value types and Reference types.
Value Types | Reference Types |
---|---|
Value type variable directly contain the data. | Reference type variables are object references.They only contain a reference to the data and not the data in itself. |
Value type variable are always assigned witha default value.Mostly zero. | Reference variables are defaulted to null. |
Value types cannot derive from another value type. | Reference type can have contructures,for example : Class will always have constructors defined. |
Value types are stored in stack. | Actual data referred by reference types are managed in heap memory. |
Lets understand difference between stack and heap
Stack | Heap |
---|---|
Static memory allocation. | Dyanamic memory allocation. |
Variables allocated on the stack are stored directly to the memory. | Variables allocated on the heap their memory allocated at run time. |
Vairables cannot be resized. | Vairables can be resized. |
The stack is always reserved in a LIFO order,the most recently reserved block is always the next block to be freed. | You can allocate a block at any time and free it at any time. |