Primitive Types and Variables

In This Chapter In this chapter we will get familiar with primitive types and variables in C# – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what a variable initialization is. We will get familiar with the two major sets of data types in C# – value types and reference types. Finally we will examine different types of literals and their usage.

What Is a Variable?

A typical program uses various values that change during its execution. For example, we create a program that performs some calculations on the values entered by the user. The values entered by one user will obviously be different from those entered in by another user. This means that when creating the program, the programmer does not know what values will be introduced as input, and that makes it necessary to process all possible values a user may enter.

When a user enters a new value that will be used in the process of calculation, we can preserve it (temporarily) in the random access memory of our computer. The values in this part of memory change (vary) throughout execution and this has led to their name – variables.

Data Types

Data types are sets (ranges) of values that have similar characteristics. For instance byte type specifies the set of integers in the range of [0 … 255].

Characteristics

Data types are characterized by:

·         Name – for example, int;

·         Size (how much memory they use) – for example, 4 bytes;

·        Default value – for example 0.

 

Types

Basic data types in C# are distributed into the following types:

·         Integer types –sbyte, byte, short, ushort, int, uint, long, ulong;

·         Real floating-point types – float, double;

·         Real type with decimal precision – decimal;

·         Boolean type – bool;

·         Character type – char;

·         String – string;

·         Object type – object.

These data types are called primitive (built-in types), because they are embedded in C# language at the lowest level. The table below represents the above mentioned data types, their range and their default values: