Data Types in C sharp
Data Types in C sharp
• Value Types
• Reference Types
• Pointer Types (Advanced, used in unsafe code)
2. Value Types
Value types directly contain their data in memory and are stored on the stack. When assigned to
another variable, a copy of the value is made. In C#, the Value Data Types will directly store the
variable value in memory, and it will also accept both signed and unsigned literals.
There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in
signed or unsigned form.
Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float
variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is
treated as double.
Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To
initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by
default floating data types are the double type.
It has to be assigned either true or false value. Values of type bool are not converted
implicitly or explicitly (with casts) to any other type. But the programmer can easily
write conversion code.
• char (16-bit Unicode): Stores a single character. Default value is \0 (null character).
• char letter = 'A';
The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has
28-29 digit Precision. To initialize a decimal variable, use the suffix m or M.
Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.
3. Reference Types
Reference type store memory addresses of objects on the heap. When assigned to another variable,
only the reference is copied. The Reference Data Types will contain a memory address of variable
value because the reference types won’t store the variable value directly in memory. When you
create a reference type variable, such as an object or a string, you are storing a reference (or pointer)
to the location in memory where the data is held. The actual data for reference types is stored on
the heap. The heap is a large pool of memory used for dynamic memory allocation. The built-in
reference types are string and object.
3.1 Object (object)
In C#, all types, predefined and user-defined, reference types and value types, inherit
directly or indirectly from Object. So basically it is the base class for all the data types
in C#. Before assigning values, it needs type conversion. When a variable of a value
type is converted to object, it’s called boxing. When a variable of type object is
converted to a value type, it’s called unboxing. Its type name is System.Object.
3.3 Arrays