C# - Constants and Literals. The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.
1. @ 2010 Tata McGraw-Hill Education
1
Education
Literals, Variables and Data TypesLiterals, Variables and Data Types
2. @ 2010 Tata McGraw-Hill Education
2
Education
Introduction
A C# program is basically a collection of classes. A class is defi ned by a set
of declaration statements and methods containing instructions known as
executable statements. These instructions are formed using certain
symbols and words according to some rigid rules known as syntax rules (or
grammar). The smallest, non-reducible, textual elements in a program are
referred to as tokens. The compiler recognizes them for building up
expressions and statements. In simple terms, a C# program is a collection of
tokens, comments and white spaces. C# includes the following five types of
tokens:Keywords
Operators
Identifiers
Punctuators
Literals
White spaces and comments are not tokens, though they may act as
separators for tokens. Keywords are an essential part of a language defi
nition. They implement specific features of the language. They are
reserved, and cannot be used as identifiers except when they are prefaced
by the @ character
3. @ 2010 Tata McGraw-Hill Education
3
Education
Identifiers are programmer-designed tokens. They are used for naming
classes, methods, variables, labels, namespaces, interfaces, etc. C# identifiers
enforce the following rules:
They can have alphabets, digits and underscore characters
They must not begin with a digit
Upper case and lower case letters are distinct
Keywords in stand-alone mode cannot be used as identifiers
Literals are the way in which the values that are stored in variables are
represented. We shall discuss these in detail in the next section
4. @ 2010 Tata McGraw-Hill Education
4
Education
Operators are symbols used in expressions to describe operations involving
one or more operands. Operators are considered in detail in Chapter 5.
Punctuators are symbols used for grouping and separating code. They defi
ne the shape and function of a program. Punctuators (also known as
separators) in C# include:
Parentheses ( )
Braces { }
Brackets [ ]
Semicolons ;
Colon:
Comma ,
Period .
5. @ 2010 Tata McGraw-Hill Education
5
Education
LITERALS
Literals are value constants assigned to variables (or results of expressions) in a
program. C# supports several types of literals as illustrated in Fig. 4.1.
6. @ 2010 Tata McGraw-Hill Education
6
Education
Integer Literals
An integer literal refers to a sequence of digits. There are two types of integers,
namely, decimal integers and hexadecimal integers.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus
sign. Valid examples of decimal integer literals are:
123 -321 0 654321
Embedded spaces, commas and non-digit characters are not permitted between digits.
For example, 15 750 20,000 $1000 are illegal numbers.
A sequence of digits preceded by 0x or 0X is considered as a hexadecimal integer (hex
integer). It may also include alphabets A through F or ‘a’ through ‘f’. A letter A
through F represents the numbers 10 through 15. Following are the examples of valid
hex integers. 0X2 0X9F 0Xbcd 0x
7. @ 2010 Tata McGraw-Hill Education
7
Education
Real Literals
Integer literals are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures, prices and so on. These quantities are represented by
numbers containing fractional parts like 17.548. Such numbers are called real (or
floating point) numbers. Further examples of real literals are:
0.0083 -0.75 435.36
These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part, which is an integer. It is possible that the number
may not have digits before the decimal point, or digits after the decimal point. That is,
215. .95 -.71 are all valid real literals.
Boolean Literals
There are two Boolean literal values:
True False
They are used as values of relational expressions.
8. @ 2010 Tata McGraw-Hill Education
8
Education
Single Character Literals
A single-character literal (or simply character constant) contains a single character
enclosed within a pair of single quote marks. Example of character in the examples
above constants are:
‘5’ ‘X’ ‘;’ ‘ ‘
Note that the character constant ‘5’ is not the same as the number 5. The last constant in
the example above is a blank space.
String Literals
A string literal is a sequence of characters enclosed between double quotes.The
characters may be alphabets, digits, special characters and blank spaces. Examples
are:
“Hello C#” “2001” “WELL DONE” “?...!” “5+3” “X”
9. @ 2010 Tata McGraw-Hill Education
9
Education
Backslash Character Literal
C# supports some special backslash character constants that are used in output methods.
For example, the symbol ‘n’ stands for a new-line character. A list of such backslash
character literals is given in Table 4.2. Note that each one
represents one character, although they consist of two characters. These character
combinations are known as escape sequences.
10. @ 2010 Tata McGraw-Hill Education
10
Education
Program 4.2 prints the various numeric literals available in C#, such as Integer,
Double and Exponential.
11. @ 2010 Tata McGraw-Hill Education
11
Education
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value.
Unlike constants that remain unchanged during the execution of a program, a variable
may take different values at different times during the execution of the program.
Every variable has a type that determines what values can
be stored in the variable. A variable name can be chosen by the programmer in a
meaningful way so as to reflect what it represents in the program. Some examples of
variable names are:
average
height
total_height
Class Strength
12. @ 2010 Tata McGraw-Hill Education
12
Education
As mentioned earlier, variable names may consist of alphabets, digits and the
underscore ( _ ), subject to the following conditions:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct. This means that the variable Total is
not the same as total or TOTAL.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
13. @ 2010 Tata McGraw-Hill Education
13
Education
DATA TYPES
Data types specify the size and type of values that can be stored. C# is a language rich
in its data types. The variety available allows the programmer to
select the type appropriate to the needs of the application. The types in C# are
primarily divided into two categories:
Value types
Reference types
Value types and reference types differ in two characteristics:
Where they are stored in the memory
How they behave in the context of assignment statements
15. @ 2010 Tata McGraw-Hill Education
15
Education
VALUE TYPES
The value types of C# can be grouped into two categories (as shown in Fig. 4.2),
namely,
User-defined types (or complex types) and
Predefined types (or simple types)
We can define our own complex types known as user-defined value types which
include struct types and enumerations. They are discussed in Chapter 11. Predefined
value types which are also known as simple types (or primitive types) are further
subdivided into:
Numeric types,
Boolean types, and
Character types.
16. @ 2010 Tata McGraw-Hill Education
16
Education
Note: C# 2.0 added a new type
called nullable type. This type
variable can hold an undefined value
Any value type variable can be defined
as a nullable type.
17. @ 2010 Tata McGraw-Hill Education
17
Education
Integral Types
Integral types can hold whole numbers such as 123, –96 and 5639. The size of the
values that can be stored depends on the integral data type we choose. C# supports the
concept of unsigned types and therefore it supports eight types of integers as shown in
Figs 4.4 and 4.5.
18. @ 2010 Tata McGraw-Hill Education
18
Education
Signed Integers
Signed integer types can hold both positive and negative numbers. Table 4.3 shows
the memory size and range of all the four signed integer data types.(Note that one byte
is equal to eight bits).
19. @ 2010 Tata McGraw-Hill Education
19
Education
Unsigned Integers
We can increase the size of the positive value stored in an integer type by making it
‘unsigned’. For example, a 16-bit short integer can store values in the range –32,768 to
32,767. However, by making it ushort, it can handle values in the range 0 to 65,535.
Table 4.4 shows the size and range of all the four unsigned integer data types.
20. @ 2010 Tata McGraw-Hill Education
20
Education
Floating-Point Types
Integer types can hold only whole numbers and therefore we use another type known
as fl oating-point type to hold numbers containing fractional parts such as 27.59 and –
1.375. There are two kinds of fl oating point storage in C#
as shown in Fig. 4.6.
21. @ 2010 Tata McGraw-Hill Education
21
Education
Decimal Type
The decimal type is a high precision, 128-bit data type that is designed for use in
financial and monetary calculations. It can store values in the range 1.0 ∞ 10–28 to 7.9
∞ 1028 with 28 significant digits. Note that the precision is given in digits, not in
decimal places.
Character Type
In order to store single characters in memory, C# provides a character data type called
char. The char type assumes a size of two bytes but, in fact it can hold only a single
character. It has been designed to hold a 16-bit Unicode character, in which the 8-bit
ASCII code is a subset.
Boolean Type
Boolean type is used when we want to test a particular condition during the execution
of the program. There are only two values that a Boolean type can take: true or
false. Remember, both these words have been declared as keywords.
22. @ 2010 Tata McGraw-Hill Education
22
Education
REFERENCE TYPES
As with value types, the reference types can also be divided into two groups:
User-defined (or complex types)
Predefined (or simple types)
User-defined reference types refer to those types which we define using predefi ned
types. They include:
Classes
Delegates
Interfaces
Arrays
These complex types will be discussed in later chapters when we take up these topics
individually. Predefined reference types include two data types:
Object type String type
23. @ 2010 Tata McGraw-Hill Education
23
Education
DECLARATION OF VARIABLES
Variables are the names of storage locations. After designing suitable variable names,
we must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration (in the program) decides the scope of the variable.
A variable must be declared before it is used in the program.
The general form of declaration of a variable is:
type Variable1, Variable2, ……VariableN;
Variables are separated by commas, A declaration statement must end with a
semicolon.
24. @ 2010 Tata McGraw-Hill Education
24
Education
INITIALIZATION OF VARIABLES
A variable must be given a value after it has been declared but before it is used in an
expression. A simple method of giving value to a variable is through the assignment
statement as follows: variableName = value;
Examples:
initial Value = O;
final Value = 100;
yes = ‘x’;
DEFAULT VALUES
A variable is either explicitly assigned a value or automatically assigned a default
value. The following categories of variables are automatically initialized to their
default values:
Static variables Instance variables Array elements
26. @ 2010 Tata McGraw-Hill Education
26
Education
CONSTANT VARIABLES
The variables whose values do not change during the execution of a program are
known as constants. For example, the variables representing the maximum number of
rows and columns of a matrix or number of students in a class in a program may not
change during execution of the program. Such variables can be made unmodifiable by
using the const keyword while initializing them.
Example:
const int ROWS = 10;
const int COLS = 20;
const int NUM = 90
27. @ 2010 Tata McGraw-Hill Education
27
Education
SCOPE OF VARIABLES
The scope of a variable is the region of code within which the variable can be
accessed. This depends on the type of the variable and place of its declaration. C#
defines several categories of variables. They include:
Static variables
Instance variables
Array elements
Value parameters
Reference parameters
Output parameters
Local variables
28. @ 2010 Tata McGraw-Hill Education
28
Education
This code contains the following variables:
m as a static variable
n as an instance variable
x as a value parameter
y as a reference parameter
z as an output parameter
a[0] as an array element
j as a local variable
Static and instance variables are declared at the class level and are known as fields or
field variables. The scope of these variables begins at the place of their declaration
and ends when the Main method terminates.
29. @ 2010 Tata McGraw-Hill Education
29
Education
BOXING AND UNBOXING
In object-oriented programming, methods are invoked using objects. Since value types
such as int and long are not objects, we cannot use them to call methods. C# enables
us to achieve this through a technique known as boxing .
Boxing
Any type, value or reference can be assigned to an object without an explicit
conversion. When the compiler finds a value type where it needs a reference type, it
creates an object ‘box’ into which it places the value of the value type. The following
code illustrates boxing:
int m = 100;
object om = m; // creates a box to hold m
When executed, this code creates a temporary reference_type ‘box’ for the object on
heap. We can also use a C-style cast for boxing.
int m = 100;
object om = m; // creates a box to hold m
30. @ 2010 Tata McGraw-Hill Education
30
Education
Unboxing
Unboxing is the process of converting the object type back to the value type.
Remember that we can only unbox a variable that has previously been boxed. In
contrast to boxing, unboxing is an explicit operation using C-style casting
int m = 10;
object om = m; //box m
int n = (int)om; //unbox om back to an int
When unboxing a value, we have to ensure that the value type is large enough to hold
the value of the object. Otherwise, the operation may result in a runtime error. For
example, the code
int m = 500;
object om = m;
byte n = (byte)om;