Mod 2
Mod 2
Mod 2
Module 2
3. Overview: In this module we will get familiar with primitive types and variables in C# –
what they are and how to work with them.
4. Objectives:
Introduction
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
You would be able to see the declaration and initialization of a variable in detail in sections
"Declaring Variables" and "Initialization of Variables" below, and it would become clear from the
examples.
In the code snippet above, we demonstrate the use of integer types. For small numbers we
use byte type, and for very large – ulong. We use unsigned types because all used values are
positive numbers.
Real Floating-Point Types
Real types in C# are the real numbers we know from mathematics. They are represented
by a floating-point according to the standard IEEE 754 and are float and double. Let’s consider in
details these two data types and understand what their similarities and differences are.
Real Type Float
The first type we will consider is the 32-bit real floating-point type float. It is also known
as a single precision real number. Its default value is 0.0f or 0.0F (both are equivalent). The
character 'f' when put at the end explicitly indicates that the number is of type float (because by
default all real numbers are considered double). More about this special suffix we can read bellow
in the "Real Literals" section. The considered type has accuracy up to seven decimal places (the
others are lost). For instance, if the number 0.123456789 is stored as type float it will be rounded
to 0.1234568. The range of values, which can be included in a float type (rounded with accuracy
of 7 significant decimal digits), range from ±1.5 × 10-45 to ±3.4 × 1038 .
Special Values of the Real Types
The real data types have also several special values that are not real numbers but are
mathematical abstractions:
- Negative infinity -∞ (Single.NegativeInfinity). It is obtained when for instance we are dividing -
1.0f by 0.0f.
- Positive infinity +∞ (Single.PositiveInfinity). It is obtained when for instance we are dividing
1.0f by 0.0f.
- Uncertainty (Single.NaN) – means that an invalid operation is performed on real numbers. It is
obtained when for example we divide 0.0f by 0.0f, as well as when calculating square root of a
negative number.
Real Type Double
The second real floating-point type in the C# language is the double type. It is also called
double precision real number and is a 64-bit type with a default value of 0.0d and 0.0D (the suffix
'd' is not mandatory because by default all real numbers in C# are of type double). This type has
precision of 15 to 16 decimal digits. The range of values, which can be recorded in double (rounded
with precision of 15-16 significant decimal digits), is from ±5.0 × 10-324 to ±1.7 × 10308 .
The smallest real value of type double is the constant Double.MinValue = -1.79769e+308
and the largest is Double.MaxValue = 1.79769e+308. The closest to 0 positive number of type
double is Double.Epsilon = 4.94066e324. As with the type float the variables of type double can
take the special values: Double.PositiveInfinity (+∞), Double.NegativeInfinity (-∞) and
Double.NaN (invalid number).
Real Floating-Point Types – Example
Here is an example in which we declare variables of real number types, assign values to
them and print them:
Since mathematics and physics mostly work with extremely large numbers (positive and
negative) and with extremely small numbers (very close to zero), real types in computing and
electronic devices must be stored and processed appropriately. For example, according to the
physics the mass of electron is approximately 9.109389*10-31 kilograms and in 1 mole of
substance there are approximately 6.02*1023 atoms. Both these values can be stored easily in float
and double types.
Due to its flexibility, the modern floating-point representation of real numbers allows us to
work with a maximum number of significant digits for very large numbers (for example, positive
and negative numbers with hundreds of digits) and with numbers very close to zero (for example,
positive and negative numbers with hundreds of zeros after the decimal point before the first
significant digit).
Consider an example in which we declare several variables of the known real types,
initialize them and print their values on the console. The purpose of the example is to illustrate
the difference in their accuracy:
Boolean Type
Boolean type is declared with the keyword bool. It has two possible values: true and false.
Its default value is false. It is used most often to store the calculation result of logical expressions.
In the example above, we declare two variables of type int, compare them and assign the result
to the bool variable greaterAB. Similarly, we do the same for the variable equalA1. If the
variable greaterAB is true, then A > B is printed on the console, otherwise A <= B is printed.
Character Type
Character type is a single character (16-bit number of a Unicode table character). It is
declared in C# with the keyword char. The Unicode table is a technological standard that represents
any character (letter, punctuation, etc.) from all human languages as writing systems (all languages
and alphabets) with an integer or a sequence of integers. More about the Unicode table can be
found in the chapter "Strings and Text Processing". The smallest possible value of a char variable
is 0, and the largest one is 65535. The values of type char are letters or other characters, and are
enclosed in apostrophes.
Strings
Strings are sequences of characters. In C# they are declared by the keyword string. Their
default value is null. Strings are enclosed in quotation marks. Various text-processing operations
can be performed using strings: concatenation (joining one string with another), splitting by a given
separator, searching, replacement of characters and others. More information about text processing
can be found in the chapter "Strings and Text Processing", where you will find detailed explanation
on what a string is, what its applications are and how we can use it.
Strings – Example
Consider an example in which we declare several variables of type string, initialize them
and print their values on the console:
// Declare some variables
string firstName = "John";
string lastName = "Smith";
string fullName = firstName + " " + lastName;
// Print the results on the console Console.WriteLine("Hello, " + firstName + "!");
Console.WriteLine("Your full name is " + fullName + ".");
// Console output:
// Hello, John!
// Your full name is John Smith.
Object Type
Object type is a special type, which is the parent of all other types in the .NET Framework.
Declared with the keyword object, it can take values from any other type. It is a reference type,
i.e. an index (address) of a memory area which stores the actual value.
Using Objects – Example
Consider an example in which we declare several variables of type object, initialize them
and print their values on the console:
// Declare some variables
object container1 = 5;
object container2 = "Five";
// Print the results on the console
Console.WriteLine("The value of container1 is: " + container1);
Console.WriteLine("The value of container2 is: " + container2);
// Console output:
// The value of container1 is: 5
// The value of container2 is: Five.
As you can see from the example, we can store the value of any other type in an object type
variable. This makes the object type a universal data container.
Variables
After reviewing the main data types in C# let’s see how we can use them. In order to work
with data we should use variables. We have already seen their usage in the examples, but now let’s
look at them in more detail.
A variable is a container of information, which can change its value. It provides means for: -
storing information; - retrieving the stored information;
- modifying the stored information.
In C# programming, you will use variables to store and process information all the time.
Characteristics of Variables
A variable is a named area of memory, which stores a value from a particular data type, and that
area of memory is accessible in the program by its name. Variables can be stored directly in the
operational memory of the program (in the stack) or in the dynamic memory in which larger objects
are stored (such as character strings and arrays).
Primitive data types (numbers, char, bool) are called value types because they store their value
directly in the program stack.
Reference data types (such as strings, objects and arrays) are an address, pointing to the dynamic
memory where their value is stored. They can be dynamically allocated and released i.e. their size
is not fixed in advance contrary to the case of value types. More information about the value and
reference data types is provided in the section "Value and Reference Types".
Naming Variables – Rules
When we want the compiler to allocate a memory area for some information which is used in our
program we must provide a name for it. It works like an identifier and allows referring to the
relevant memory area. The name of the variable can be any of our choice but must follow certain
rules defined in the C# language specification:
- Variable names can contain the letters a-z, A-Z, the digits 0-9 as well as the character '_'.
- Variable names cannot start with a digit.
- Variable names cannot coincide with a keyword of the C# language. For example, base, char,
default, int, object, this, null and many others cannot be used as variable names.
A list of the C# keywords can be found in the section "Keywords" in chapter "Introduction to
Programming". If we want to name a variable like a keyword, we can add a prefix to the name –
"@". For example, @char and @null are valid variable names while char and null are invalid.
Proper names:
- name
- first_Name
- _name1
We will provide some recommendations how to name your variables, since not all names, allowed
by the compiler, are appropriate for the variables.
- The names should be descriptive and explain what the variable is used for. For example, an
appropriate name for a variable storing a person’s name is personName and inappropriate name is
a37.
- Only Latin characters should be used. Although Cyrillic is allowed by the compiler, it is not a
good practice to use it in variable names or in the rest of the identifiers within the program.
- In C# it is generally accepted that variable names should start with a small letter and include
small letters, every new word, however, starts with a capital letter. For instance, the name
firstName is correct and better to use than firstname or first_name. Usage of the character _ in the
variable names is considered a bad naming style.
- Variable names should be neither too long nor too short – they just need to clarify the purpose of
the variable within its context.
- Uppercase and lowercase letters should be used carefully as C# distinguishes them. For instance,
age and Age are different variables.
And here are some examples for poorly named variables (although the names are correct from
the C# compiler’s perspective):
- _firstName (starts with _)
- last_name (contains _)
- AGE (is written with capital letters)
- Start_Index (starts with capital letter and contains _)
- lastNegativeNumber_Index (contains _)
- a37 (the name is not descriptive and does not clearly provide the purpose of the variable)
- fullName23, fullName24, etc. (it is not appropriate for a variable name to contain digits unless
this improves the clarity of the variable used; if you need to have multiple variables with similar
names ending in a different number, storing the same or similar type of data, it may be more
appropriate to create a single collection or array variable and name it fullNamesList, for example).
Declaring Variables
string name;
int age
Assigning a Value
Assigning a value to a variable is the act of providing a value that must be stored in the variable.
This operation is performed by the assignment operator "=". On the left side of the operator we
put the variable name and on the right side – its new value.
Here is an example of assigning values to variables:
name = "John Smith";
age = 25;
Initialization of Variables
The word initialization in programming means specifying an initial value. When setting value to
variables at the time of their declaration we actually initialize them.
Each data type in C# has a default value (default initialization) which is used when there is no
explicitly set value for a given variable. We can use the following table to see the default values
of the types, which we already got familiar with:
Value types are stored in the program execution stack and directly contain their value. Value
types are the primitive numeric types, the character type and the Boolean type: sbyte, byte, short,
ushort, int, long, ulong, float, double, decimal, char, bool. The memory allocated for them is
released when the program exits their range, i.e. when the block of code in which they are defined
completes its execution. For example, a variable declared in the method Main() of the program is
stored in the stack until the program completes execution of this method, i.e. until it finishes (C#
programs terminate after fully executing the Main() method).
Reference types keep a reference (address), in the program execution stack, and that reference
points to the dynamic memory (heap), where their value is stored. The reference is a pointer
(address of the memory cell) indicating the actual location of the value in the heap. An example of
a value at address in the stack for execution is 0x00AD4934. The reference has a type. The
reference can only point to objects of the same type, i.e. it is a strongly typed pointer. All reference
types can hold a null value. This is a special service value, which means that there is no value.
Reference types allocate dynamic memory for their creation. They also release some dynamic
memory for a memory cleaning (garbage collector), when it is no longer used by the program. It
is unknown exactly when a given reference variable will be released of the garbage collector as
this depends on the memory load and other factors. Since the allocation and release of memory is
a slow operation, it can be said that the reference types are slower than the value ones.
As reference data types are allocated and released dynamically during program execution, their
size might not be known in advance. For example, a variable of type string can contain text data
which varies in length. Actually the string text value is stored in the dynamic memory and can
occupy a different volume (count of bytes) while the string variable stores the address of the text
value.
Reference types are all classes, arrays and interfaces such as the types: object, string, byte[]. We
will learn about classes, objects, strings, arrays and interfaces in the next chapters of this book. For
now, it is enough to know that all types, which are not value, are reference and their values are
stored in the heap (the dynamically allocated memory).
In this example we will illustrate how value and reference types are represented in memory.
Consider the execution of the following programming code:
int i = 42;
char ch = 'A';
bool result = true;
object obj = 42;
string str = "Hello";
byte[] bytes = { 1, 2, 3 };
Literals
Primitive types, which we already met, are special data types built into the C# language. Their
values specified in the source code of the program are called literals. One example will make this
clearer:
In the above example, literals are true, 'C', 100, 20000 and 300000. They are variable values set
directly in the source code of the program.
Types of Literals
In C# language, there are several types of literals:
- Boolean
- Integer
- Real
- Character
- String
- Object literal null
Boolean Literals
When we assign a value to a variable of type bool we can use only one of these two values or a
Boolean expression (which is calculated to true or false).
Here is an example of a declaration of a variable of type bool and assigning a value, which
represents the Boolean literal true:
Integer Literals
Integer literals are sequences of digits, a sign (+, -), suffixes and prefixes. Using prefixes we can
present integers in the program source in decimal or hexadecimal format. More information about
the different numeral systems we can find in the chapter "Numeral Systems". In the integer literals
the following prefixes and suffixes may take part:
- "0x" and "0X" as prefix indicates hexadecimal values, for example 0xA8F1;
- 'l' and 'L' as suffix indicates long type data, for example 357L.
- 'u' and 'U' as suffix indicates uint or ulong data type, for example 112u.
By default (if no suffix is used) the integer literals are of type int.
Real literals are a sequence of digits, a sign (+, -), suffixes and the decimal point character. We
use them for values of type float, double and decimal. Real literals can be represented in
exponential format. They also use the following indications:
- 'f' and 'F' as suffixes mean data of type float;
- 'd' and 'D' as suffixes mean data of type double;
- 'm' and 'm' as suffixes mean data of type decimal;
- 'e' is an exponent, for example, "e-5" means the integer part multiplied by 10-5 .
By default (if there is no suffix), the real numbers are of type double.
Character Literals
Character literals are single characters enclosed in apostrophes (single quotes). We use them to
set the values of type char. The value of a character literal can be:
Escaping Sequences
Sometimes it is necessary to work with characters that are not displayed on the keyboard or with
characters that have special meanings, such as the “new line” character. They cannot be
represented directly in the source code of the program and in order to use them we need special
techniques, which we will discuss now.
Escaping sequences are literals. They are a sequence of special characters, which describe a
character that cannot be written directly in the source code. This is, for instance, the “new line”
character. There are many examples of characters that cannot be represented directly in the source
code: a double quotation mark, tab, new line, backslash and others. Here are some of the most
frequently used escaping sequences:
- \' – single quote
- \" – double quotes
- \\ – backslash
- \n – new line
- \t – offset (tab)
- \uXXXX – char specified by its Unicode number, for example \u03A7.
The character \ (backslash) is also called an escaping character because it allows the display on
screen (or other output device) of characters that have special meaning or effect and cannot be
represented directly in the source code.
String Literals
String literals are used for data of type string. They are a sequence of characters enclosed in double
quotation marks.
All the escaping rules for the char type discussed above are also valid for string literals.
Strings can be preceded by the @ character that specifies a quoted string (verbatim string). In
quoted strings the rules for escaping are not valid, i.e. the character \ means \ and is not an escaping
character. Only one character needs to be escaped in the quoted strings – the character " (double-
quotes) and it is escaped in the following way – by repeating it "" (double doublequotes). All other
characters are treated literally, even the new line. Quoted strings are often used for the file system
paths naming.
More about strings we will find in the chapter "Strings and Text Processing".
Exercises
1. Declare several variables by selecting for each one of them the most appropriate of the
types sbyte, byte, short, ushort, int, uint, long and ulong in order to assign them the following
values: 52,130; -115; 4825932; 97; -10000; 20000; 224; 970,700,000; 112; -44; -1,000,000; 1990;
123456789123456789.
2. Which of the following values can be assigned to variables of type float, double and
decimal: 5, -5.01, 34.567839023; 12.345; 8923.1234857; 3456.091124875956542151256683467?
3. Write a program, which compares correctly two real numbers with accuracy at least
0.000001.
4. Initialize a variable of type int with a value of 256 in hexadecimal format (256 is 100 in a
numeral system with base 16).
5. Declare a variable of type char and assign it as a value the character, which has Unicode
code, 72 (use the Windows calculator in order to find hexadecimal representation of 72).
Grading System
Output =50%
Mid-Term/Final Examination =25%
Quizzes =15%
Attendance =10%
100%
7. References
Doyle, Barbara (2012). C# Programming, Problem Analysis to Program Design, Cengage
Learning.
Sofia, (2013). Fundamentals of Computer Programming with C#. Nakov, Svetlin & Co.
LORENA P. FLORITA
College Instructor
Noted:
Approved by: