Basic Data Types and their mapping to CTS (Common Type System)
There are two kinds of data type in C#.
Value Type (implicit data types, structs and enumeration).
Reference Type (objects, delegates).
value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only their reference (handle). Implicit datatypes are defined in the language core by the language vendor, while explicit data types are types that are by using or composing implicit data types.
As we saw in the first issue, implicit data types in .Net compliant languages are mapped to types
in the Common Type System (CTS) and CLS (Common Language Specification). Hence, each implicit data type in C# has its corresponding .Net type. The implicit data types in C# are:
Implicit data types are represented in language using keywords, so each of the above is a keyword in C#
(Keyword are the words defined by the language and can not be used as identifiers). It is worth noting that string is also an implicit data type in C#, so string is a keyword in C#. The last point about implicit data types is that they are value types and thus stored on the stack, while user defined types or referenced types are stored using the heap. A stack is a data structure that store items in a first out (FIFO) fashion. It is an area of memory supported by the processor and its size is determined at the compile time. A heap consists of memory available to the program at run time. Reference types are allocated using memory available from the heap dynamically (during the execution of program). The garbage collector searches for non-referenced data in heap during the execution of program and return that space to Operating System.
Variables
During the execution of a program, data is temporarily stored in memory. A variable is the name given to a memory location holding a particular type of data. So, each variable has associated with it a data type and a value.
e.g.,
The above line will reserve an area of 4 bytes in memory to store an integer type values, which will be referred to in the rest of program by the identifier 'i'. You can initialize the variable as you declare it (on the fly) and can also declare/initialize multiple variable of the same type in a single statement, e.g.,
In C# (like other modern languages), you must declare variables before using them. Also, there is the concept of "Definite Assignment" in C# which says "local variables (variables defined in a method) must be initialized before being used". The following program won't compile:
but, if you un-comment the 2nd line, the program will compile. C# does not assign default values to local variables. C# is also a type safe language, i.e., values of particular data can only be stored in their respective (or compatible) data type. You can't store integer values in Boolean data types like we used to do in C/C++.